text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
module es { export class MathHelper { public static readonly Epsilon: number = 0.00001; public static readonly Rad2Deg = 57.29578; public static readonly Deg2Rad = 0.0174532924; /** * 表示pi除以2的值(1.57079637) */ public static readonly PiOver2 = Math.PI / 2; /** * 将弧度转换成角度。 * @param radians 用弧度表示的角 */ public static toDegrees(radians: number) { return radians * 57.295779513082320876798154814105; } /** * 将角度转换为弧度 * @param degrees */ public static toRadians(degrees: number) { return degrees * 0.017453292519943295769236907684886; } /** * 返回由给定三角形和两个归一化重心(面积)坐标定义的点的一个轴的笛卡尔坐标 * @param value1 * @param value2 * @param value3 * @param amount1 * @param amount2 */ public static barycentric(value1: number, value2: number, value3: number, amount1: number, amount2: number) { return value1 + (value2 - value1) * amount1 + (value3 - value1) * amount2; } /** * 使用指定位置执行Catmull-Rom插值 * @param value1 * @param value2 * @param value3 * @param value4 * @param amount */ public static catmullRom(value1: number, value2: number, value3: number, value4: number, amount: number) { // 使用来自http://www.mvps.org/directx/articles/catmull/的公式 let amountSquared = amount * amount; let amountCubed = amountSquared * amount; return (0.5 * (2 * value2 + (value3 - value1) * amount + (2 * value1 - 5 * value2 + 4 * value3 - value4) * amountSquared + (3 * value2 - value1 - 3 * value3 + value4) * amountCubed)); } /** * 将值(在leftMin-leftMax范围内)映射到一个在rightMin-rightMax范围内的值 * @param value * @param leftMin * @param leftMax * @param rightMin * @param rightMax */ public static map(value: number, leftMin: number, leftMax: number, rightMin: number, rightMax: number) { return rightMin + (value - leftMin) * (rightMax - rightMin) / (leftMax - leftMin); } /** * 将值从任意范围映射到0到1范围 * @param value * @param min * @param max * @returns */ public static map01(value: number, min: number, max: number) { return (value - min) * 1 / (max - min); } /** * 将值从某个任意范围映射到1到0范围 * 这相当于map01的取反 * @param value * @param min * @param max * @returns */ public static map10(value: number, min: number, max: number) { return 1 - this.map01(value, min, max); } /** * 使用三次方程在两个值之间进行插值 * @param value1 * @param value2 * @param amount */ public static smoothStep(value1: number, value2: number, amount: number) { let result = this.clamp(amount, 0, 1); result = MathHelper.hermite(value1, 0, value2, 0, result); return result; } /** * 将给定角度减小到π到-π之间的值 * @param angle */ public static wrapAngle(angle: number) { if ((angle > -Math.PI) && (angle <= Math.PI)) return angle; angle %= Math.PI * 2; if (angle <= -Math.PI) return angle + 2 * Math.PI; if (angle > Math.PI) return angle - 2 * Math.PI; return angle; } /** * 确定值是否以2为底 * @param value * @returns */ public static isPowerOfTwo(value: number) { return (value > 0) && ((value % (value - 1)) == 0); } public static lerp(from: number, to: number, t: number) { return from + (to - from) * this.clamp01(t); } public static betterLerp(a: number, b: number, t: number, epsilon: number): number { return Math.abs(a - b) < epsilon ? b : MathHelper.lerp(a, b, t); } /** * 使度数的角度在a和b之间 * 用于处理360度环绕 * @param a * @param b * @param t * @returns */ public static lerpAngle(a: number, b: number, t: number) { let num = this.repeat(b - a, 360); if (num > 180) num -= 360; return a + num * this.clamp01(t); } /** * 使弧度的角度在a和b之间 * @param a * @param b * @param t * @returns */ public static lerpAngleRadians(a: number, b: number, t: number) { let num = this.repeat(b - a, Math.PI * 2); if (num > Math.PI) num -= Math.PI * 2; return a + num * this.clamp01(t); } /** * 循环t使其不大于长度且不小于0 * @param t * @param length * @returns */ public static pingPong(t: number, length: number) { t = this.repeat(t, length * 2); return length - Math.abs(t - length); } /** * 如果value> = threshold返回其符号,否则返回0 * @param value * @param threshold * @returns */ public static signThreshold(value: number, threshold: number) { if (Math.abs(value) >= threshold) return Math.sign(value); else return 0; } public static inverseLerp(from: number, to: number, t: number) { if (from < to) { if (t < from) return 0; else if (t > to) return 1; } else { if (t < to) return 1; else if (t > from) return 0; } return (t - from) / (to - from); } /** * 在两个值之间线性插值 * 此方法是MathHelper.Lerp的效率较低,更精确的版本。 */ public static lerpPrecise(value1: number, value2: number, amount: number) { return ((1 - amount) * value1) + (value2 * amount); } public static clamp(value: number, min: number, max: number) { if (value < min) return min; if (value > max) return max; return value; } public static snap(value: number, increment: number) { return Math.round(value / increment) * increment; } /** * 给定圆心、半径和角度,得到圆周上的一个点。0度是3点钟。 * @param circleCenter * @param radius * @param angleInDegrees */ public static pointOnCirlce(circleCenter: Vector2, radius: number, angleInDegrees: number) { let radians = MathHelper.toRadians(angleInDegrees); return new Vector2(Math.cos(radians) * radians + circleCenter.x, Math.sin(radians) * radians + circleCenter.y); } /** * 如果值为偶数,返回true * @param value */ public static isEven(value: number) { return value % 2 == 0; } /** * 如果值是奇数,则返回true * @param value * @returns */ public static isOdd(value: number) { return value % 2 != 0; } /** * 将值四舍五入并返回它和四舍五入后的数值 * @param value * @param roundedAmount * @returns */ public static roundWithRoundedAmount(value: number, roundedAmount: Ref<number>) { let rounded = Math.round(value); roundedAmount.value = value - (rounded * Math.round(value / rounded)); return rounded; } /** * 数值限定在0-1之间 * @param value */ public static clamp01(value: number) { if (value < 0) return 0; if (value > 1) return 1; return value; } public static angleBetweenVectors(from: Vector2, to: Vector2) { return Math.atan2(to.y - from.y, to.x - from.x); } public static angleToVector(angleRadians: number, length: number) { return new Vector2(Math.cos(angleRadians) * length, Math.sin(angleRadians) * length); } /** * 增加t并确保它总是大于或等于0并且小于长度 * @param t * @param length */ public static incrementWithWrap(t: number, length: number) { t++; if (t == length) return 0; return t; } /** * 递减t并确保其始终大于或等于0且小于长度 * @param t * @param length * @returns */ public static decrementWithWrap(t: number, length: number) { t--; if (t < 0) return length - 1; return t; } /** * 返回sqrt(x * x + y * y) * @param x * @param y * @returns */ public static hypotenuse(x: number, y: number) { return Math.sqrt(x * x + y * y); } public static closestPowerOfTwoGreaterThan(x: number) { x--; x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); return (x + 1); } /** * 以roundToNearest为步长,将值舍入到最接近的数字。例如:在125中找到127到最近的5个结果 * @param value * @param roundToNearest */ public static roundToNearest(value: number, roundToNearest: number) { return Math.round(value / roundToNearest) * roundToNearest; } /** * 检查传递的值是否在某个阈值之下。对于小规模、精确的比较很有用 * @param value * @param ep */ public static withinEpsilon(value: number, ep: number = this.Epsilon) { return Math.abs(value) < ep; } /** * 由上移量向上移。start可以小于或大于end。例如:开始是2,结束是10,移位是4,结果是6 * @param start * @param end * @param shift */ public static approach(start: number, end: number, shift: number): number { if (start < end) return Math.min(start + shift, end); return Math.max(start - shift, end); } /** * 通过偏移量钳位结果并选择最短路径,将起始角度向终止角度移动,起始值可以小于或大于终止值。 * 示例1:开始是30,结束是100,移位是25,结果为55 * 示例2:开始是340,结束是30,移位是25,结果是5(365换为5) * @param start * @param end * @param shift * @returns */ public static approachAngle(start: number, end: number, shift: number) { let deltaAngle = this.deltaAngle(start, end); if (-shift < deltaAngle && deltaAngle < shift) return end; return this.repeat(this.approach(start, start + deltaAngle, shift), 360); } /** * 将 Vector 投影到另一个 Vector 上 * @param other */ public static project(self: Vector2, other: Vector2) { let amt = self.dot(other) / other.lengthSquared(); let vec = other.scale(amt); return vec; } /** * 通过将偏移量(全部以弧度为单位)夹住结果并选择最短路径,起始角度朝向终止角度。 * 起始值可以小于或大于终止值。 * 此方法的工作方式与“角度”方法非常相似,唯一的区别是使用弧度代替度,并以2 * Pi代替360。 * @param start * @param end * @param shift * @returns */ public static approachAngleRadians(start: number, end: number, shift: number) { let deltaAngleRadians = this.deltaAngleRadians(start, end); if (-shift < deltaAngleRadians && deltaAngleRadians < shift) return end; return this.repeat(this.approach(start, start + deltaAngleRadians, shift), Math.PI * 2); } /** * 使用可接受的检查公差检查两个值是否大致相同 * @param value1 * @param value2 * @param tolerance * @returns */ public static approximately(value1: number, value2: number, tolerance: number = this.Epsilon) { return Math.abs(value1 - value2) <= tolerance; } /** * 计算两个给定角之间的最短差值(度数) * @param current * @param target */ public static deltaAngle(current: number, target: number) { let num = this.repeat(target - current, 360); if (num > 180) num -= 360; return num; } /** * 检查值是否介于最小值/最大值(包括最小值/最大值)之间 * @param value * @param min * @param max * @returns */ public static between(value: number, min: number, max: number) { return value >= min && value <= max; } /** * 计算以弧度为单位的两个给定角度之间的最短差 * @param current * @param target * @returns */ public static deltaAngleRadians(current: number, target: number) { let num = this.repeat(target - current, 2 * Math.PI); if (num > Math.PI) num -= 2 * Math.PI; return num; } /** * 循环t,使其永远不大于长度,永远不小于0 * @param t * @param length */ public static repeat(t: number, length: number) { return t - Math.floor(t / length) * length; } public static floorToInt(f: number) { return Math.trunc(Math.floor(f)); } /** * 将值绕一圈移动的助手 * @param position * @param speed * @returns */ public static rotateAround(position: Vector2, speed: number) { let time = Time.totalTime * speed; let x = Math.cos(time); let y = Math.sin(time); return new Vector2(position.x + x, position.y + y); } /** * 旋转是相对于当前位置而不是总旋转。 * 例如,如果您当前处于90度并且想要旋转到135度,则可以使用45度而不是135度的角度 * @param point * @param center * @param angleIndegrees */ public static rotateAround2(point: Vector2, center: Vector2, angleIndegrees: number) { angleIndegrees = this.toRadians(angleIndegrees); let cos = Math.cos(angleIndegrees); let sin = Math.sin(angleIndegrees); let rotatedX = cos * (point.x - center.x) - sin * (point.y - center.y) + center.x; let rotatedY = sin * (point.x - center.x) + cos * (point.y - center.y) + center.y; return new Vector2(rotatedX, rotatedY); } /** * 根据圆的中心,半径和角度在圆的圆周上得到一个点。 0度是3点钟方向 * @param circleCenter * @param radius * @param angleInDegrees */ public static pointOnCircle(circleCenter: Vector2, radius: number, angleInDegrees: number) { let radians = this.toRadians(angleInDegrees); return new Vector2(Math.cos(radians) * radius + circleCenter.x, Math.sin(radians) * radius + circleCenter.y); } /** * 根据圆的中心,半径和角度在圆的圆周上得到一个点。 0弧度是3点钟方向 * @param circleCenter * @param radius * @param angleInRadians * @returns */ public static pointOnCircleRadians(circleCenter: Vector2, radius: number, angleInRadians: number) { return new Vector2(Math.cos(angleInRadians) * radius + circleCenter.x, Math.sin(angleInRadians) * radius + circleCenter.y); } /** * lissajou曲线 * @param xFrequency * @param yFrequency * @param xMagnitude * @param yMagnitude * @param phase * @returns */ public static lissajou(xFrequency: number = 2, yFrequency: number = 3, xMagnitude: number = 1, yMagnitude: number = 1, phase: number = 0) { let x = Math.sin(Time.totalTime * xFrequency + phase) * xMagnitude; let y = Math.cos(Time.totalTime * yFrequency) * yMagnitude; return new Vector2(x, y); } /** * lissajou曲线的阻尼形式,其振荡随时间在0和最大幅度之间。 * 为获得最佳效果,阻尼应在0到1之间。 * 振荡间隔是动画循环的一半完成的时间(以秒为单位)。 * @param xFrequency * @param yFrequency * @param xMagnitude * @param yMagnitude * @param phase * @param damping * @param oscillationInterval * @returns */ public static lissajouDamped(xFrequency: number = 2, yFrequency: number = 3, xMagnitude: number = 1, yMagnitude: number = 1, phase: number = 0.5, damping: number = 0, oscillationInterval: number = 5) { let wrappedTime = this.pingPong(Time.totalTime, oscillationInterval); let damped = Math.pow(Math.E, -damping * wrappedTime); let x = damped * Math.sin(Time.totalTime * xFrequency + phase) * xMagnitude; let y = damped * Math.cos(Time.totalTime * yFrequency) * yMagnitude; return new Vector2(x, y); } /** * 执行Hermite样条插值 * @param value1 * @param tangent1 * @param value2 * @param tangent2 * @param amount * @returns */ public static hermite(value1: number, tangent1: number, value2: number, tangent2: number, amount: number) { let v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; let sCubed = s * s * s; let sSquared = s * s; if (amount == 0) result = value1; else if (amount == 1) result = value2; else result = (2 * v1 - 2 * v2 + t2 + t1) * sCubed + (3 * v2 - 3 * v1 - 2 * t1 - t2) * sSquared + t1 * s + v1; return result; } /** * 此函数用于确保数不是NaN或无穷大 * @param x * @returns */ public static isValid(x: number) { if (Number.isNaN(x)) { return false; } return x !== Infinity; } public static smoothDamp(current: number, target: number, currentVelocity: number, smoothTime: number, maxSpeed: number, deltaTime: number): { value: number; currentVelocity: number } { smoothTime = Math.max(0.0001, smoothTime); const num: number = 2 / smoothTime; const num2: number = num * deltaTime; const num3: number = 1 / (1 + (num2 + (0.48 * (num2 * num2) + 0.235 * (num2 * (num2 * num2))))); let num4: number = current - target; const num5: number = target; const num6: number = maxSpeed * smoothTime; num4 = this.clamp(num4, num6 * -1, num6); target = current - num4; const num7: number = (currentVelocity + num * num4) * deltaTime; currentVelocity = (currentVelocity - num * num7) * num3; let num8: number = target + (num4 + num7) * num3; if (num5 - current > 0 === num8 > num5) { num8 = num5; currentVelocity = (num8 - num5) / deltaTime; } return { value: num8, currentVelocity }; } public static smoothDampVector(current: Vector2, target: Vector2, currentVelocity: Vector2, smoothTime: number, maxSpeed: number, deltaTime: number): Vector2 { const v = Vector2.zero; const resX = this.smoothDamp( current.x, target.x, currentVelocity.x, smoothTime, maxSpeed, deltaTime ); v.x = resX.value; currentVelocity.x = resX.currentVelocity; const resY = this.smoothDamp( current.y, target.y, currentVelocity.y, smoothTime, maxSpeed, deltaTime ); v.y = resY.value; currentVelocity.y = resY.currentVelocity; return v; } /** * 将值(在 leftMin - leftMax 范围内)映射到 rightMin - rightMax 范围内的值 * @param value * @param leftMin * @param leftMax * @param rightMin * @param rightMax * @returns */ public static mapMinMax(value: number, leftMin: number, leftMax: number, rightMin: number, rightMax): number { return rightMin + ((MathHelper.clamp(value, leftMin, leftMax) - leftMin) * (rightMax - rightMin)) / (leftMax - leftMin); } public static fromAngle(angle: number) { return new Vector2(Math.cos(angle), Math.sin(angle)).normalizeEqual(); } } }
the_stack
import {Constructor, PolyDictionary} from '../../../../types/GlobalTypes'; import {CoreString} from '../../../../core/String'; import {BaseNodeType} from '../../_Base'; import {NodeEvent} from '../../../poly/NodeEvent'; import {NodeContext} from '../../../poly/NodeContext'; import {NameController} from '../NameController'; import {CoreNodeSelection} from '../../../../core/NodeSelection'; import {Poly} from '../../../Poly'; import {ParamsInitData} from '../io/IOController'; import {CoreGraphNodeId} from '../../../../core/graph/CoreGraph'; import {BaseOperationContainer} from '../../../operations/container/_Base'; import {SopOperationContainer} from '../../../operations/container/sop'; import {BaseSopOperation} from '../../../operations/sop/_Base'; type OutputNodeFindMethod = (() => BaseNodeType) | undefined; export class HierarchyChildrenController { private _children: PolyDictionary<BaseNodeType> = {}; private _children_by_type: PolyDictionary<CoreGraphNodeId[]> = {}; private _children_and_grandchildren_by_context: PolyDictionary<CoreGraphNodeId[]> = {}; private _selection: CoreNodeSelection | undefined; get selection(): CoreNodeSelection { return (this._selection = this._selection || new CoreNodeSelection(this.node)); } constructor(protected node: BaseNodeType, private _context: NodeContext) {} dispose() { const children = this.children(); for (let child of children) { this.node.removeNode(child); } this._selection = undefined; } get context() { return this._context; } // // // OUTPUT NODE // // private _output_node_find_method: (() => BaseNodeType) | undefined; set_output_node_find_method(method: OutputNodeFindMethod) { this._output_node_find_method = method; } output_node() { if (this._output_node_find_method) { return this._output_node_find_method(); } } // // // // // set_child_name(node: BaseNodeType, new_name: string): void { let current_child_with_name; new_name = CoreString.sanitizeName(new_name); if ((current_child_with_name = this._children[new_name]) != null) { // only return if found node is same as argument node, and if new_name is same as current_name if (node.name() === new_name && current_child_with_name.graphNodeId() === node.graphNodeId()) { return; } // increment new_name new_name = CoreString.increment(new_name); return this.set_child_name(node, new_name); } else { const current_name = node.name(); // delete old entry if node was in _children with old name const current_child = this._children[current_name]; if (current_child) { delete this._children[current_name]; } // add to new name this._children[new_name] = node; node.nameController.update_name_from_parent(new_name); this._add_to_nodesByType(node); this.node.scene().nodesController.addToInstanciatedNode(node); } } node_context_signature() { return `${this.node.context()}/${this.node.type()}`; } available_children_classes() { return Poly.registeredNodes(this._context, this.node.type()); } is_valid_child_type(node_type: string): boolean { const node_class = this.available_children_classes()[node_type]; return node_class != null; } // create_node(node_type: string, params_init_value_overrides?: ParamsInitData): BaseNodeType { // const node_class = this.available_children_classes()[node_type]; // if (node_class == null) { // const message = `child node type '${node_type}' not found for node '${this.node.path()}'. Available types are: ${Object.keys( // this.available_children_classes() // ).join(', ')}, ${this._context}, ${this.node.type}`; // console.error(message); // throw message; // } else { // const child_node = new node_class(this.node.scene, `child_node_${node_type}`, params_init_value_overrides); // child_node.initialize_base_and_node(); // this.add_node(child_node); // child_node.lifecycle.set_creation_completed(); // return child_node; // } // } createNode<K extends BaseNodeType>( node_class_or_string: string | Constructor<K>, params_init_value_overrides?: ParamsInitData, node_type = '' ): K { if (typeof node_class_or_string == 'string') { const node_class = this._find_node_class(node_class_or_string); return this._create_and_init_node(node_class, params_init_value_overrides, node_type) as K; } else { return this._create_and_init_node(node_class_or_string, params_init_value_overrides, node_type); } } private _create_and_init_node<K extends BaseNodeType>( node_class: Constructor<K>, params_init_value_overrides?: ParamsInitData, node_type = '' ) { const child_node = new node_class(this.node.scene(), `child_node_${node_type}`, params_init_value_overrides); child_node.initialize_base_and_node(); this.add_node(child_node); child_node.lifecycle.set_creation_completed(); return child_node; } private _find_node_class(node_type: string) { const node_class = this.available_children_classes()[node_type.toLowerCase()]; if (node_class == null) { const message = `child node type '${node_type}' not found for node '${this.node.path()}'. Available types are: ${Object.keys( this.available_children_classes() ).join(', ')}, ${this._context}, ${this.node.type()}`; console.error(message); throw message; } return node_class; } create_operation_container( operation_type: string, operation_container_name: string, params_init_value_overrides?: ParamsInitData ): BaseOperationContainer<any> { const operation_class = Poly.registeredOperation(this._context, operation_type); if (operation_class == null) { const message = `no operation found with context ${this._context}/${operation_type}`; console.error(message); throw message; } else { const operation = new operation_class(this.node.scene()) as BaseSopOperation; const operation_container = new SopOperationContainer( operation, operation_container_name, params_init_value_overrides || {} ); return operation_container; } } add_node(child_node: BaseNodeType) { child_node.setParent(this.node); child_node.params.init(); child_node.parentController.onSetParent(); child_node.nameController.run_post_set_fullPath_hooks(); if (child_node.childrenAllowed() && child_node.childrenController) { for (let child of child_node.childrenController.children()) { child.nameController.run_post_set_fullPath_hooks(); } } this.node.emit(NodeEvent.CREATED, {child_node_json: child_node.toJSON()}); if (this.node.scene().lifecycleController.onCreateHookAllowed()) { child_node.lifecycle.run_on_create_hooks(); } child_node.lifecycle.run_on_add_hooks(); this.set_child_name(child_node, NameController.base_name(child_node)); this.node.lifecycle.run_on_child_add_hooks(child_node); if (child_node.require_webgl2()) { this.node.scene().webgl_controller.set_require_webgl2(); } this.node.scene().missingExpressionReferencesController.check_for_missing_references(child_node); return child_node; } removeNode(child_node: BaseNodeType): void { if (child_node.parent() != this.node) { return console.warn(`node ${child_node.name()} not under parent ${this.node.path()}`); } else { if (this.selection.contains(child_node)) { this.selection.remove([child_node]); } const first_connection = child_node.io.connections.firstInputConnection(); const input_connections = child_node.io.connections.inputConnections(); const output_connections = child_node.io.connections.outputConnections(); if (input_connections) { for (let input_connection of input_connections) { if (input_connection) { input_connection.disconnect({setInput: true}); } } } if (output_connections) { for (let output_connection of output_connections) { if (output_connection) { output_connection.disconnect({setInput: true}); if (first_connection) { const old_src = first_connection.node_src; const old_output_index = output_connection.output_index; const old_dest = output_connection.node_dest; const old_input_index = output_connection.input_index; old_dest.io.inputs.setInput(old_input_index, old_src, old_output_index); } } } } // remove from children child_node.setParent(null); delete this._children[child_node.name()]; this._remove_from_nodesByType(child_node); this.node.scene().nodesController.removeFromInstanciatedNode(child_node); // set other dependencies dirty // Note that this call to set_dirty was initially before this._children_node.remove_graph_input // but that prevented the obj/geo node to properly clear its sop_group if this was the last node // if (this._is_dependent_on_children && this._children_node) { // this._children_node.set_successors_dirty(this.node); // } child_node.setSuccessorsDirty(this.node); // disconnect successors child_node.graphDisconnectSuccessors(); this.node.lifecycle.run_on_child_remove_hooks(child_node); child_node.lifecycle.run_on_delete_hooks(); child_node.dispose(); child_node.emit(NodeEvent.DELETED, {parent_id: this.node.graphNodeId()}); } } _add_to_nodesByType(node: BaseNodeType) { const node_id = node.graphNodeId(); const type = node.type(); this._children_by_type[type] = this._children_by_type[type] || []; if (!this._children_by_type[type].includes(node_id)) { this._children_by_type[type].push(node_id); } this.add_to_children_and_grandchildren_by_context(node); } _remove_from_nodesByType(node: BaseNodeType) { const node_id = node.graphNodeId(); const type = node.type(); if (this._children_by_type[type]) { const index = this._children_by_type[type].indexOf(node_id); if (index >= 0) { this._children_by_type[type].splice(index, 1); if (this._children_by_type[type].length == 0) { delete this._children_by_type[type]; } } } this.remove_from_children_and_grandchildren_by_context(node); } add_to_children_and_grandchildren_by_context(node: BaseNodeType) { const node_id = node.graphNodeId(); const type = node.context(); this._children_and_grandchildren_by_context[type] = this._children_and_grandchildren_by_context[type] || []; if (!this._children_and_grandchildren_by_context[type].includes(node_id)) { this._children_and_grandchildren_by_context[type].push(node_id); } const parent = this.node.parent(); if (parent && parent.childrenAllowed()) { parent.childrenController?.add_to_children_and_grandchildren_by_context(node); } } remove_from_children_and_grandchildren_by_context(node: BaseNodeType) { const node_id = node.graphNodeId(); const type = node.context(); if (this._children_and_grandchildren_by_context[type]) { const index = this._children_and_grandchildren_by_context[type].indexOf(node_id); if (index >= 0) { this._children_and_grandchildren_by_context[type].splice(index, 1); if (this._children_and_grandchildren_by_context[type].length == 0) { delete this._children_and_grandchildren_by_context[type]; } } } const parent = this.node.parent(); if (parent && parent.childrenAllowed()) { parent.childrenController?.remove_from_children_and_grandchildren_by_context(node); } } nodesByType(type: string): BaseNodeType[] { const node_ids = this._children_by_type[type] || []; const graph = this.node.scene().graph; const nodes: BaseNodeType[] = []; for (let node_id of node_ids) { const node = graph.nodeFromId(node_id) as BaseNodeType; if (node) { nodes.push(node); } } return nodes; } child_by_name(name: string) { return this._children[name]; } has_children_and_grandchildren_with_context(context: NodeContext) { return this._children_and_grandchildren_by_context[context] != null; } children(): BaseNodeType[] { return Object.values(this._children); } children_names() { return Object.keys(this._children).sort(); } traverse_children(callback: (arg0: BaseNodeType) => void) { for (let child of this.children()) { callback(child); child.childrenController?.traverse_children(callback); } } }
the_stack
import { AVLTree, MapEntry, RNG, VMContext } from ".."; let tree: AVLTree<u32, u32>; let _closure_var1: u32; let _closure_rng: RNG<u32>; function random(n: i32): u32[] { const a = new Array<u32>(n); _closure_rng = new RNG<u32>(2 * n); return a.map<u32>((_): u32 => _closure_rng.next()); } function range(start: u32, end: u32): u32[] { return new Array<u32>(end - start).map<u32>((_, i) => i); } function maxTreeHeight(n: f64): u32 { // From near-sdk-rs TreeMap: // h <= C * log2(n + D) + B // where: // C =~ 1.440, D =~ 1.065, B =~ 0.328 // (source: https://en.wikipedia.org/wiki/AVL_tree) const B: f64 = -0.328; const C: f64 = 1.44; const D: f64 = 1.065; const h = C * Math.log2(n + D) + B; return Math.ceil(h) as u32; } // Convenience method for tests that insert then remove some values function insertThenRemove( t: AVLTree<u32, u32>, keysToInsert: u32[], keysToRemove: u32[] ): void { const map = new Map<u32, u32>(); insertKeys(t, keysToInsert, map); removeKeys(t, keysToRemove, map); } function insertKeys( t: AVLTree<u32, u32>, keysToInsert: u32[], map: Map<u32, u32> | null = null ): void { for (let i = 0; i < keysToInsert.length; ++i) { const key = keysToInsert[i]; expect(t.has(key)).toBeFalsy( "tree.has() should return false for key that has not been inserted yet. Are duplicate keys being inserted?" ); t.insert(key, i); expect(t.getSome(key)).toStrictEqual(i); if (map) { map.set(key, i); expect(t.getSome(key)).toStrictEqual(map.get(key)); } } } function removeKeys( t: AVLTree<u32, u32>, keysToRemove: u32[], map: Map<u32, u32> | null = null ): void { for (let i = 0; i < keysToRemove.length; ++i) { const key = keysToRemove[i]; if (map && map.has(key)) { expect(t.getSome(key)).toStrictEqual(map.get(key)); map.delete(key); } t.remove(key); expect(t.has(key)).toBeFalsy( "tree.has() should return false for removed key" ); } } function generateRandomTree(t: AVLTree<u32, u32>, n: u32): Map<u32, u32> { const map = new Map<u32, u32>(); const keysToInsert = random(2 * n); const keysToRemove: u32[] = []; for (let i = 0; i < i32(n); ++i) { keysToRemove.push(keysToInsert[i]); } insertKeys(t, keysToInsert, map); removeKeys(t, keysToRemove, map); return map; } describe("AVLTrees should handle", () => { beforeEach(() => { tree = new AVLTree<u32, u32>("tree1"); }); it("adds key-value pairs", () => { const key = 1; const value = 2; tree.set(key, value); expect(tree.has(key)).toBeTruthy("The tree should have the key"); expect(tree.containsKey(key)).toBeTruthy("The tree should contain the key"); expect(tree.getSome(key)).toStrictEqual(value); }); it("checks for non-existent keys", () => { const key = 1; expect(tree.has(key)).toBeFalsy("tree should not have the key"); expect(tree.containsKey(key)).toBeFalsy("tree should not contain the key"); }); throws("if attempting to get a non-existent key", () => { const key = 1; tree.getSome(key); }); it("is empty", () => { const key = 42; _closure_var1 = key; expect(tree.size).toStrictEqual(0); expect(tree.height).toStrictEqual(0); expect(tree.has(key)).toBeFalsy("empty tree should not have the key"); expect(tree.containsKey(key)).toBeFalsy( "empty tree should not have the key" ); expect(() => { tree.min(); }).toThrow("min() should throw for empty tree"); expect(() => { tree.max(); }).toThrow("max() should throw for empty tree"); expect(() => { tree.lower(_closure_var1); }).toThrow("lower() should throw for empty tree"); expect(() => { tree.lower(_closure_var1); }).toThrow("higher() should throw for empty tree"); }); it("rotates left twice when inserting 3 keys in decreasing order", () => { expect(tree.height).toStrictEqual(0); tree.insert(3, 3); expect(tree.height).toStrictEqual(1); tree.insert(2, 2); expect(tree.height).toStrictEqual(2); tree.insert(1, 1); expect(tree.height).toStrictEqual(2); expect(tree.rootKey).toStrictEqual(2); }); it("rotates right twice when inserting 3 keys in increasing order", () => { expect(tree.height).toStrictEqual(0); tree.insert(1, 1); expect(tree.height).toStrictEqual(1); tree.insert(2, 2); expect(tree.height).toStrictEqual(2); tree.insert(3, 3); expect(tree.height).toStrictEqual(2); expect(tree.rootKey).toStrictEqual(2); }); it("sets and gets n key-value pairs in ascending order", () => { const n: u32 = 30; const cases: u32[] = range(0, n * 2); let counter = 0; for (let i = 0; i < cases.length; ++i) { const k = cases[i]; if (k % 2 === 0) { counter += 1; debug(); tree.insert(k, counter); } } counter = 0; for (let i = 0; i < cases.length; ++i) { const k = cases[i]; if (k % 2 === 0) { counter += 1; expect(tree.getSome(k)).toStrictEqual(counter); } else { expect(tree.has(k)).toBeFalsy(`tree should not contain key ${k}`); } } expect(tree.height).toBeLessThanOrEqual(maxTreeHeight(n)); }); it("sets and gets n key-value pairs in descending order", () => { const n: u32 = 30; const cases: u32[] = range(0, n * 2).reverse(); let counter = 0; for (let i = 0; i < cases.length; ++i) { const k = cases[i]; if (k % 2 === 0) { counter += 1; tree.insert(k, counter); } } counter = 0; for (let i = 0; i < cases.length; ++i) { const k = cases[i]; if (k % 2 === 0) { counter += 1; expect(tree.getSome(k)).toStrictEqual(counter); } else { expect(tree.has(k)).toBeFalsy(`tree should not contain key ${k}`); } } expect(tree.height).toBeLessThanOrEqual(maxTreeHeight(n)); }); it("sets and gets n random key-value pairs", () => { VMContext.setPrepaid_gas(u64.MAX_VALUE); // TODO setup free gas env to prevent gas exceeded error, and test larger trees range(1, 8).forEach((k) => { // tree size is 2^(k-1) const n = 1 << k; const input: u32[] = random(n); input.forEach((x) => { tree.insert(x, 42); }); input.forEach((x) => { expect(tree.getSome(x)).toStrictEqual(42); }); expect(tree.height).toBeLessThanOrEqual(maxTreeHeight(n)); // tree.clear(); }); }); it("gets the minimum key", () => { const n: u32 = 30; const keys = random(n); keys.forEach((x) => { tree.insert(x, 1); }); const min = (keys.sort(), keys[0]); expect(tree.min()).toStrictEqual(min); }); it("gets the maximum key", () => { const n: u32 = 30; const keys = random(n); keys.forEach((x) => { tree.insert(x, 1); }); const max = (keys.sort(), keys[keys.length - 1]); expect(tree.max()).toStrictEqual(max); }); it("gets the key lower than the given key", () => { const keys: u32[] = [10, 20, 30, 40, 50]; keys.forEach((x) => { tree.insert(x, 1); }); expect(() => { tree.lower(5); }).toThrow("5 is lower than tree.min(), which is 10"); expect(() => { tree.lower(10); }).toThrow("10 is equal to tree.min(), which is 10"); expect(tree.lower(11)).toStrictEqual(10); expect(tree.lower(20)).toStrictEqual(10); expect(tree.lower(49)).toStrictEqual(40); expect(tree.lower(50)).toStrictEqual(40); expect(tree.lower(51)).toStrictEqual(50); }); it("gets the key higher than the given key", () => { const keys: u32[] = [10, 20, 30, 40, 50]; keys.forEach((x) => { tree.insert(x, 1); }); expect(tree.higher(5)).toStrictEqual(10); expect(tree.higher(10)).toStrictEqual(20); expect(tree.higher(11)).toStrictEqual(20); expect(tree.higher(20)).toStrictEqual(30); expect(tree.higher(49)).toStrictEqual(50); expect(() => { tree.higher(50); }).toThrow("50 is equal to tree.max(), which is 50"); expect(() => { tree.higher(51); }).toThrow("51 is greater than tree.max(), which is 50"); }); it("gets the key lower than or equal to the given key", () => { const keys: u32[] = [10, 20, 30, 40, 50]; keys.forEach((x) => { tree.insert(x, 1); }); expect(() => { tree.floorKey(5); }).toThrow("5 is lower than tree.min(), which is 10"); expect(tree.floorKey(10)).toStrictEqual(10); expect(tree.floorKey(11)).toStrictEqual(10); expect(tree.floorKey(20)).toStrictEqual(20); expect(tree.floorKey(49)).toStrictEqual(40); expect(tree.floorKey(50)).toStrictEqual(50); expect(tree.floorKey(51)).toStrictEqual(50); }); it("gets the key greater than or equal to the given key", () => { const keys: u32[] = [10, 20, 30, 40, 50]; keys.forEach((x) => { tree.insert(x, 1); }); expect(tree.ceilKey(5)).toStrictEqual(10); expect(tree.ceilKey(10)).toStrictEqual(10); expect(tree.ceilKey(11)).toStrictEqual(20); expect(tree.ceilKey(20)).toStrictEqual(20); expect(tree.ceilKey(49)).toStrictEqual(50); expect(tree.ceilKey(50)).toStrictEqual(50); expect(() => { tree.ceilKey(51); }).toThrow("51 is greater than tree.max(), which is 50"); }); it("removes 1 key", () => { const key = 1; const value = 2; tree.insert(key, value); expect(tree.getSome(key)).toStrictEqual(value); expect(tree.size).toStrictEqual(1); tree.remove(key); expect(tree.has(key)).toBeFalsy(`tree should not contain key ${key}`); expect(tree.size).toStrictEqual(0); }); it("removes non-existent key", () => { const key = 1; const value = 2; tree.insert(key, value); expect(tree.getSome(key)).toStrictEqual(value); expect(tree.size).toStrictEqual(1); tree.remove(value); expect(tree.getSome(key)).toStrictEqual(value); expect(tree.size).toStrictEqual(1); }); it("removes 3 keys in descending order", () => { const keys: u32[] = [3, 2, 1]; insertThenRemove(tree, keys, keys); expect(tree.size).toStrictEqual(0); }); it("removes 3 keys in ascending order", () => { const keys: u32[] = [1, 2, 3]; insertThenRemove(tree, keys, keys); expect(tree.size).toStrictEqual(0); }); it("removes 7 random keys", () => { const keys: u32[] = [ 2104297040, 552624607, 4269683389, 3382615941, 155419892, 4102023417, 1795725075, ]; insertThenRemove(tree, keys, keys); expect(tree.size).toStrictEqual(0); }); // test_remove_7_regression_2() it("removes 9 random keys", () => { const keys: u32[] = [ 1186903464, 506371929, 1738679820, 1883936615, 1815331350, 1512669683, 3581743264, 1396738166, 1902061760, ]; insertThenRemove(tree, keys, keys); expect(tree.size).toStrictEqual(0); }); it("removes 20 random keys", () => { const keys: u32[] = [ 552517392, 3638992158, 1015727752, 2500937532, 638716734, 586360620, 2476692174, 1425948996, 3608478547, 757735878, 2709959928, 2092169539, 3620770200, 783020918, 1986928932, 200210441, 1972255302, 533239929, 497054557, 2137924638, ]; insertThenRemove(tree, keys, keys); expect(tree.size).toStrictEqual(0); }); // test_remove_7_regression() it("inserts 8 keys then removes 4 keys", () => { const keysToInsert: u32[] = [882, 398, 161, 76]; const keysToRemove: u32[] = [242, 687, 860, 811]; insertThenRemove(tree, keysToInsert.concat(keysToRemove), keysToRemove); expect(tree.size).toStrictEqual(keysToInsert.length); keysToInsert.forEach((key, i) => { expect(tree.getSome(key)).toStrictEqual(i); }); }); it("removes n random keys", () => { const n: u32 = 20; const keys = random(n); const set = new Set<u32>(); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; tree.insert(key, i); set.add(key); } expect(tree.size).toStrictEqual(set.size); keys.forEach((key, i) => { expect(tree.getSome(key)).toStrictEqual(i); tree.remove(key); expect(tree.has(key)).toBeFalsy(`tree should not contain key ${key}`); }); expect(tree.size).toStrictEqual(0); }); it("removes the root of the tree", () => { tree.insert(2, 1); tree.insert(3, 1); tree.insert(1, 1); tree.insert(4, 1); expect(tree.rootKey).toStrictEqual(2); tree.remove(2); expect(tree.rootKey).toStrictEqual(3); expect(tree.getSome(1)).toStrictEqual(1); expect(() => { tree.getSome(2); }).toThrow("tree should throw when getting removed key (root of the tree)"); expect(tree.getSome(3)).toStrictEqual(1); expect(tree.getSome(4)).toStrictEqual(1); }); it("inserts 2 keys then removes 2 keys", () => { const keysToInsert: u32[] = [11760225, 611327897]; const keysToRemove: u32[] = [2982517385, 1833990072]; insertThenRemove(tree, keysToInsert, keysToRemove); expect(tree.height).toBeLessThanOrEqual(maxTreeHeight(tree.size)); }); it("inserts n duplicate keys", () => { range(0, 30).forEach((key, i) => { tree.insert(key, i); tree.insert(42, i); }); expect(tree.getSome(42)).toStrictEqual(29); // most recent value inserted for key 42 expect(tree.size).toStrictEqual(31); }); it("inserts 2n keys then removes n random keys", () => { range(1, 4).forEach((k) => { const set = new Set<u32>(); const n = 1 << k; const keysToInsert = random(n); const keysToRemove = random(n); const allKeys = keysToInsert.concat(keysToRemove); insertThenRemove(tree, allKeys, keysToRemove); for (let i = 0; i < allKeys.length; ++i) { const key = allKeys[i]; set.add(key); } for (let i = 0; i < keysToRemove.length; ++i) { const key = allKeys[i]; set.delete(key); } expect(tree.size).toStrictEqual(set.size); expect(tree.height).toBeLessThanOrEqual(maxTreeHeight(n)); tree.clear(); expect(tree.size).toStrictEqual(0); }); }); it("does nothing when removing while empty", () => { expect(tree.size).toStrictEqual(0); tree.remove(1); expect(tree.size).toStrictEqual(0); }); it("returns an equivalent array", () => { tree.insert(1, 41); tree.insert(2, 42); tree.insert(3, 43); const a = [ new MapEntry<u32, u32>(1, 41), new MapEntry<u32, u32>(2, 42), new MapEntry<u32, u32>(3, 43), ]; expect(tree.entries(1, 4)).toStrictEqual(a); expect(tree.entries(1, 3, true)).toStrictEqual(a); }); it("returns an empty array when empty", () => { expect(tree.entries(0, 0)).toStrictEqual([]); }); it("returns a range of values for a given start key and end key", () => { const keys = [10, 20, 30, 40, 50, 45, 35, 25, 15, 5]; const values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (let i = 0; i < keys.length; ++i) { const key = keys[i]; tree.insert(key, values[i]); } expect(tree.values(20, 30)).toStrictEqual([2, 8]); expect(tree.values(11, 41)).toStrictEqual([9, 2, 8, 3, 7, 4]); expect(tree.values(20, 41)).toStrictEqual([2, 8, 3, 7, 4]); expect(tree.values(21, 45)).toStrictEqual([8, 3, 7, 4]); expect(tree.values(26, 30)).toStrictEqual([]); expect(tree.values(25, 25)).toStrictEqual([8]); expect(tree.values(26, 25)).toStrictEqual([]); expect(tree.values(40, 50)).toStrictEqual([4, 6]); expect(tree.values(40, 51)).toStrictEqual([4, 6, 5]); expect(tree.values(4, 5)).toStrictEqual([]); expect(tree.values(5, 51)).toStrictEqual([10, 1, 9, 2, 8, 3, 7, 4, 6, 5]); }); it("returns a range of values for a given start key and inclusive end key", () => { const keys = [10, 20, 30, 40, 50, 45, 35, 25, 15, 5]; const values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (let i = 0; i < keys.length; ++i) { const key = keys[i]; tree.insert(key, values[i]); } expect(tree.values(20, 30, true)).toStrictEqual([2, 8, 3]); expect(tree.values(11, 41, true)).toStrictEqual([9, 2, 8, 3, 7, 4]); expect(tree.values(20, 41, true)).toStrictEqual([2, 8, 3, 7, 4]); expect(tree.values(21, 45, true)).toStrictEqual([8, 3, 7, 4, 6]); expect(tree.values(26, 30, true)).toStrictEqual([3]); expect(tree.values(25, 25, true)).toStrictEqual([8]); expect(tree.values(26, 25, true)).toStrictEqual([]); expect(tree.values(40, 50, true)).toStrictEqual([4, 6, 5]); expect(tree.values(40, 51, true)).toStrictEqual([4, 6, 5]); expect(tree.values(4, 5, true)).toStrictEqual([10]); expect(tree.values(5, 51, true)).toStrictEqual([ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5, ]); }); it("remains balanced after some insertions and deletions", () => { const keysToInsert: u32[] = [2, 3, 4]; const keysToRemove: u32[] = [0, 0, 0, 1]; insertThenRemove(tree, keysToInsert, keysToRemove); // @ts-ignore expect(tree.isBalanced()).toBeTruthy(); }); it("remains balanced after more insertions and deletions", () => { const keysToInsert: u32[] = [1, 2, 0, 3, 5, 6]; const keysToRemove: u32[] = [0, 0, 0, 3, 5, 6, 7, 4]; insertThenRemove(tree, keysToInsert, keysToRemove); // @ts-ignore expect(tree.isBalanced()).toBeTruthy(); }); it("remains balanced and sorted after 2n insertions and n deletions", () => { VMContext.setPrepaid_gas(u64.MAX_VALUE); // TODO setup free gas env to prevent gas exceeded error, and test larger trees const n: u32 = 33; const map = generateRandomTree(tree, n); const sortedKeys: u32[] = map.keys().sort(); const sortedValues: u32[] = []; for (let i = 0; i < sortedKeys.length; ++i) { sortedValues.push(map.get(sortedKeys[i])); } expect(tree.size).toStrictEqual(n); // @ts-ignore expect(tree.isBalanced()).toBeTruthy(); expect(tree.height).toBeLessThanOrEqual(maxTreeHeight(n)); expect(tree.keys(u32.MIN_VALUE, u32.MAX_VALUE)).toStrictEqual(sortedKeys); expect(tree.values(u32.MIN_VALUE, u32.MAX_VALUE)).toStrictEqual( sortedValues ); }); });
the_stack
import { BigNumber } from 'bignumber.js'; import { EventEmitter } from 'events'; import { FilecoinSnapApi } from '@nodefactory/filsnap-types'; declare class ActiveSync { Base: TipSet; Target: TipSet; Stage: SyncStateStage; Height: ChainEpoch; Start: string; End: string; Message: string; } declare class Actor { Code: Cid; Head: Cid; Nonce: number; Balance: BigNumber; } declare class ActorState { Balance: string; State: any; } declare type Address = string; /** * AddrInfo is a small struct used to pass around a peer with a set of addresses (and later, keys?). */ declare class AddrInfo { ID: ID; Addrs: Multiaddr[]; } declare class BaseWalletProvider { client: LotusClient; constructor(client: LotusClient); release(): Promise<any>; /** * get balance for address * @param address */ getBalance(address: string): Promise<any>; /** * get nonce for address. Note that this method may not be atomic. Use MpoolPushMessage instead. * @param address */ getNonce(address: string): Promise<number>; /** * send signed message * @param msg */ sendSignedMessage(msg: SignedMessage): Promise<Cid>; /** * estimate gas fee cap * @param message * @param nblocksincl */ estimateMessageGasFeeCap(message: Message, nblocksincl: number): Promise<string>; /** * estimate gas limit, it fails if message fails to execute. * @param message */ estimateMessageGasLimit(message: Message): Promise<number>; /** * estimate gas to succesufully send message, and have it likely be included in the next nblocksincl blocks * @param nblocksincl * @param sender * @param gasLimit */ estimateMessageGasPremium(nblocksincl: number, sender: string, gasLimit: number): Promise<string>; /** * estimate gas to succesufully send message, and have it included in the next 10 blocks * @param message */ estimateMessageGas(message: Message): Promise<Message>; /** * prepare a message for signing, add defaults, and populate nonce and gas related parameters if not provided * @param message */ createMessage(message: MessagePartial): Promise<Message>; /** * call back on chain head updates. * @param cb * @returns interval id */ chainNotify(cb: (headChange: HeadChange[]) => void): Promise<void>; /** * returns the current head of the chain */ getHead(): Promise<TipSet>; /** * returns the block specified by the given CID * @param blockCid */ getBlock(blockCid: Cid): Promise<BlockHeader>; /** * returns messages stored in the specified block. * @param blockCid */ getBlockMessages(blockCid: Cid): Promise<BlockMessages>; /** * returns receipts for messages in parent tipset of the specified block * @param blockCid */ getParentReceipts(blockCid: Cid): Promise<MessageReceipt[]>; /** * returns messages stored in parent tipset of the specified block. * @param blockCid */ getParentMessages(blockCid: Cid): Promise<WrappedMessage[]>; /** * looks back for a tipset at the specified epoch. * @param epochNumber */ getTipSetByHeight(epochNumber: number): Promise<TipSet>; /** * reads ipld nodes referenced by the specified CID from chain blockstore and returns raw bytes. * @param cid */ readObj(cid: Cid): Promise<string>; /** * checks if a given CID exists in the chain blockstore * @param cid */ hasObj(cid: Cid): Promise<boolean>; /** * returns statistics about the graph referenced by 'obj'. * * @remarks * If 'base' is also specified, then the returned stat will be a diff between the two objects. */ statObj(obj: Cid, base?: Cid): Promise<ObjStat>; /** * Returns the genesis tipset. * @param tipSet */ getGenesis(): Promise<TipSet>; /** * Computes weight for the specified tipset. * @param tipSetKey */ getTipSetWeight(tipSetKey?: TipSetKey): Promise<string>; /** * reads a message referenced by the specified CID from the chain blockstore * @param messageCid */ getMessage(messageCid: Cid): Promise<Message>; /** * Returns a set of revert/apply operations needed to get from * @param from * @param to */ getPath(from: TipSetKey, to: TipSetKey): Promise<HeadChange[]>; /** * returns the current status of the lotus sync system. */ state(): Promise<SyncState>; /** * returns a channel streaming incoming, potentially not yet synced block headers. * @param cb */ incomingBlocks(cb: (blockHeader: BlockHeader) => void): Promise<void>; /** * get all mpool messages * @param tipSetKey */ getMpoolPending(tipSetKey: TipSetKey): Promise<[SignedMessage]>; /** * returns a list of pending messages for inclusion in the next block * @param tipSetKey * @param ticketQuality */ sub(cb: (data: MpoolUpdate) => void): Promise<void>; /** * returns a signed StorageAsk from the specified miner. * @param peerId * @param miner */ queryAsk(peerId: PeerID, miner: Address): Promise<StorageAsk>; /** * returns the indicated actor's nonce and balance * @param address * @param tipSetKey */ getActor(address: string, tipSetKey?: TipSetKey): Promise<Actor>; /** * returns the indicated actor's state * @param address * @param tipSetKey */ readState(address: string, tipSetKey?: TipSetKey): Promise<ActorState>; /** * looks back and returns all messages with a matching to or from address, stopping at the given height. * @param filter * @param tipSetKey * @param toHeight */ listMessages(filter: { To?: string; From?: string; }, tipSetKey?: TipSetKey, toHeight?: number): Promise<Cid[]>; /** * returns the name of the network the node is synced to */ networkName(): Promise<NetworkName>; /** * returns info about the given miner's sectors * @param address * @param tipSetKey */ minerSectors(address: string, tipSetKey?: TipSetKey): Promise<SectorOnChainInfo[]>; /** * returns info about sectors that a given miner is actively proving. * @param address * @param tipSetKey */ minerActiveSectors(address: string, tipSetKey?: TipSetKey): Promise<SectorOnChainInfo[]>; /** * calculates the deadline at some epoch for a proving period and returns the deadline-related calculations. * @param address * @param tipSetKey */ minerProvingDeadline(address: string, tipSetKey?: TipSetKey): Promise<DeadlineInfo>; /** * returns the power of the indicated miner * @param address * @param tipSetKey */ minerPower(address: string, tipSetKey?: TipSetKey): Promise<MinerPower>; /** * returns info about the indicated miner * @param address * @param tipSetKey */ minerInfo(address: string, tipSetKey?: TipSetKey): Promise<MinerInfo>; /** * returns all the proving deadlines for the given miner * @param address * @param tipSetKey */ minerDeadlines(address: string, tipSetKey?: TipSetKey): Promise<Deadline[]>; /** * Loads miner partitions for the specified miner and deadline * @param address * @param idx * @param tipSetKey */ minerPartitions(address: string, idx?: number, tipSetKey?: TipSetKey): Promise<Partition[]>; /** * Returns a bitfield indicating the faulty sectors of the given miner * @param address * @param tipSetKey */ minerFaults(address: string, tipSetKey?: TipSetKey): Promise<BitField>; /** * returns all non-expired Faults that occur within lookback epochs of the given tipset * @param epoch * @param tipSetKey */ allMinerFaults(epoch: ChainEpoch, tipSetKey?: TipSetKey): Promise<Fault[]>; /** * returns a bitfield indicating the recovering sectors of the given miner * @param address * @param tipSetKey */ minerRecoveries(address: string, tipSetKey?: TipSetKey): Promise<BitField>; /** * returns the precommit deposit for the specified miner's sector * @param address * @param sectorPreCommitInfo * @param tipSetKey */ minerPreCommitDepositForPower(address: string, sectorPreCommitInfo: SectorPreCommitInfo, tipSetKey?: TipSetKey): Promise<string>; /** * returns the initial pledge collateral for the specified miner's sector * @param address * @param sectorPreCommitInfo * @param tipSetKey */ minerInitialPledgeCollateral(address: string, sectorPreCommitInfo: SectorPreCommitInfo, tipSetKey?: TipSetKey): Promise<string>; /** * returns the portion of a miner's balance that can be withdrawn or spent * @param address * @param tipSetKey */ minerAvailableBalance(address: string, tipSetKey?: TipSetKey): Promise<string>; /** * returns the PreCommit info for the specified miner's sector * @param address * @param sector * @param tipSetKey */ sectorPreCommitInfo(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorPreCommitOnChainInfo>; /** * StateSectorGetInfo returns the on-chain info for the specified miner's sector * @param address * @param sector * @param tipSetKey * * @remarks * NOTE: returned Expiration may not be accurate in some cases, use StateSectorExpiration to get accurate expiration epoch */ sectorGetInfo(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorOnChainInfo>; /** * returns epoch at which given sector will expire * @param address * @param sector * @param tipSetKey */ sectorExpiration(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorExpiration>; /** * finds deadline/partition with the specified sector * @param address * @param sector * @param tipSetKey */ sectorPartition(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorLocation>; /** * searches for a message in the chain and returns its receipt and the tipset where it was executed * @param cid */ searchMsg(cid: Cid): Promise<MsgLookup>; /** * returns the addresses of every miner that has claimed power in the Power Actor * @param tipSetKey */ listMiners(tipSetKey?: TipSetKey): Promise<Address[]>; /** * returns the addresses of every actor in the state * @param tipSetKey */ listActors(tipSetKey?: TipSetKey): Promise<Address[]>; /** * looks up the Escrow and Locked balances of the given address in the Storage Market * @param address * @param tipSetKey */ marketBalance(address: Address, tipSetKey?: TipSetKey): Promise<MarketBalance>; /** * returns the Escrow and Locked balances of every participant in the Storage Market * @param tipSetKey */ marketParticipants(tipSetKey?: TipSetKey): Promise<{ [k: string]: MarketBalance; }>; /** * returns information about every deal in the Storage Market * @param tipSetKey */ marketDeals(tipSetKey?: TipSetKey): Promise<{ [k: string]: MarketDeal; }>; /** * returns information about the indicated deal * @param dealId * @param tipSetKey */ marketStorageDeal(dealId: DealID, tipSetKey?: TipSetKey): Promise<MarketDeal>; /** * retrieves the ID address of the given address * @param address * @param tipSetKey */ lookupId(address: Address, tipSetKey?: TipSetKey): Promise<Address>; /** * returns the public key address of the given ID address * @param address * @param tipSetKey */ accountKey(address: Address, tipSetKey?: TipSetKey): Promise<Address>; /** * returns all the actors whose states change between the two given state CIDs * @param cid1 * @param cid2 */ changedActors(cid1?: Cid, cid2?: Cid): Promise<{ [k: string]: Actor; }>; /** * returns the message receipt for the given message * @param cid * @param tipSetKey */ getReceipt(cid: Cid, tipSetKey?: TipSetKey): Promise<MessageReceipt>; /** * returns the number of sectors in a miner's sector set and proving set * @param address * @param tipSetKey */ minerSectorCount(address: Address, tipSetKey?: TipSetKey): Promise<MinerSectors>; /** * returns the vesting details of a given multisig. * @param address * @param tipSetKey */ msigGetVestingSchedule(address: string, tipSetKey: TipSetKey): Promise<MsigVesting>; /** * returns the portion of a multisig's balance that can be withdrawn or spent * @param address * @param tipSetKey */ msigGetAvailableBalance(address: string, tipSetKey: TipSetKey): Promise<string>; /** * returns the amount of FIL that vested in a multisig in a certain period. * @param address * @param startEpoch * @param endEpoch */ msigGetVested(address: string, startEpoch: TipSetKey, endEpoch: TipSetKey): Promise<string>; } declare class BeaconEntry { Round: number; Data: []; } declare type BitField = number[]; declare class BlockHeader { Miner: string; Ticket: { VRFProof: string; }; ElectionProof: { WinCount: number; VRFProof: string; }; BeaconEntries: { Round: number; Data: string; }[]; WinPoStProof: { PoStProof: number; ProofBytes: string; }[]; Parents: Cid[]; ParentWeight: string; Height: number; ParentStateRoot: Cid; ParentMessageReceipts: Cid; Messages: Cid; BLSAggregate: Signature; Timestamp: number; BlockSig: Signature; ForkSignaling: number; } declare class BlockMessages { BlsMessages: Message[]; SecpkMessages: SignedMessage[]; Cids: Cid[]; } declare class BlockMsg { Header: BlockHeader; BlsMessages: Cid[]; SecpkMessages: Cid[]; } declare class BlockTemplate { Miner: Address; Parents: TipSetKey; Ticket: Ticket; Eproof: ElectionProof; BeaconValues: BeaconEntry[]; Messages: SignedMessage[]; Epoch: ChainEpoch; Timestamp: number; WinningPoStProof: PoStProof[]; } declare type ChainEpoch = number; /** * Payment Channel Types */ declare class ChannelAvailableFunds { /** * Address of the channel */ Channel: Address; /** * From address of the channel (channel creator) */ From: Address; /** * To address of the channel */ To: Address; /** * Amount of funds that have been confirmed on-chain for the channel */ ConfirmedAmt: string; /** * Amount of funds that are pending confirmation on-chain */ PendingAmt: string; /** * Can be used with PaychGetWaitReady to wait for confirmation of pending funds */ PendingWaitSentinel: Cid; /** * Amount that is queued up behind a pending request */ QueuedAmt: string; /** * Amount that is redeemed by vouchers on-chain and in the local datastore */ VoucherReedeemedAmt: string; } declare class ChannelInfo { Channel: Address; WaitSentinel: Cid; } declare class Cid { '/': string; } declare class CirculatingSupply { FilVested: TokenAmount; FilMined: TokenAmount; FilBurnt: TokenAmount; FilLocked: TokenAmount; FilCirculating: TokenAmount; } declare class Claim { /** * Sum of raw byte power for a miner's sectors. */ RawBytePower: StoragePower; /** * Sum of quality adjusted power for a miner's sectors. */ QualityAdjPower: StoragePower; } declare type ClientEvent = number; declare class CommPRet { Root: Cid; Size: UnpaddedPieceSize; } declare class ComputeStateOutput { Root: Cid; Trace: InvocResult[]; } declare type Connectedness = number; declare interface Connector { url: string; token?: string | undefined; disconnect(): Promise<any>; connect(): Promise<any>; request(req: RequestArguments): Promise<any>; on(event: 'connected' | 'disconnected', listener: (...args: any[]) => void): this; } declare class DataCIDSize { PayloadSize: number; PieceSize: PaddedPieceSize; PieceCID: Cid; } /** * DataRef is a reference for how data will be transferred for a given storage deal */ declare class DataRef { TransferType: string; Root: Cid; /** * Optional for non-manual transfer, will be recomputed from the data if not given */ PieceCid?: Cid; /** * Optional for non-manual transfer, will be recomputed from the data if not given */ PieceSize?: UnpaddedPieceSize; } declare class DataSize { PayloadSize: number; PieceSize: PaddedPieceSize; } declare class DataTransferChannel { TransferID: TransferID; Status: number; BaseCID: Cid; IsInitiator: boolean; IsSender: boolean; Voucher: string; Message: string; OtherPeer: PeerID; Transferred: number; } declare class Deadline { /** * Partitions in this deadline, in order. * * @remarks * The keys of this AMT are always sequential integers beginning with zero. */ Partitions: Cid; /** * Maps epochs to partitions that _may_ have sectors that expire in or before that epoch. * * @remarks * Partitions MUST NOT be removed from this queue (until the associated epoch has passed) even if they no longer have sectors expiring at that epoch. * Sectors expiring at this epoch may later be recovered, and this queue will not be updated at that time. */ ExpirationsEpochs: Cid; /** * Partitions numbers with PoSt submissions since the proving period started. */ PostSubmissions: BitField; /** * Partitions with sectors that terminated early. */ EarlyTerminations: BitField; /** * The number of non-terminated sectors in this deadline (incl faulty). */ LiveSectors: number; /** * The total number of sectors in this deadline (incl dead). */ TotalSectors: number; /** * Memoized sum of faulty power in partitions. */ FaultyPower: PowerPair; } /** * Deadline calculations with respect to a current epoch. * * @remarks * "Deadline" refers to the window during which proofs may be submitted. Windows are non-overlapping ranges [Open, Close), but the challenge epoch for a window occurs before the window opens. * The current epoch may not necessarily lie within the deadline or proving period represented here. */ declare class DeadlineInfo { /** * Epoch at which this info was calculated. */ CurrentEpoch: ChainEpoch; /** * First epoch of the proving period (<= CurrentEpoch). */ PeriodStart: ChainEpoch; /** * A deadline index, in [0..WPoStProvingPeriodDeadlines) unless period elapsed. */ Index: number; /** * First epoch from which a proof may be submitted (>= CurrentEpoch). */ Open: ChainEpoch; /** * First epoch from which a proof may no longer be submitted (>= Open). */ Close: ChainEpoch; /** * Epoch at which to sample the chain for challenge (< Open). */ Challenge: ChainEpoch; /** * First epoch at which a fault declaration is rejected (< Open). */ FaultCutoff: ChainEpoch; } declare class DealCollateralBounds { Min: TokenAmount; Max: TokenAmount; } declare type DealID = number; declare class DealInfo { ProposalCid: Cid; State: StorageDealStatus; /** * More information about deal state, particularly errors */ Message: string; Provider: Address; DataRef: DataRef; PieceCID: Cid; Size: number; PricePerEpoch: any; Duration: number; DealID: DealID; CreationTime: string; Verified: boolean; } declare class DealProposal { PieceCID: Cid; PieceSize: PaddedPieceSize; VerifiedDeal: boolean; Client: Address; Provider: Address; /** * An arbitrary client chosen label to apply to the deal */ Label: string; /** * Nominal start epoch. * @remarks * Deal payment is linear between StartEpoch and EndEpoch, with total amount StoragePricePerEpoch * (EndEpoch - StartEpoch). * Storage deal must appear in a sealed (proven) sector no later than StartEpoch, otherwise it is invalid. */ StartEpoch: ChainEpoch; EndEpoch: ChainEpoch; StoragePricePerEpoch: TokenAmount; ProviderCollateral: TokenAmount; ClientCollateral: TokenAmount; } declare class DealState { /** * @remarks * -1 if not yet included in proven sector */ SectorStartEpoch: ChainEpoch; /** * @remarks * -1 if deal state never updated */ LastUpdatedEpoch: ChainEpoch; /** * @remarks * -1 if deal never slashed */ SlashEpoch: ChainEpoch; } /** * DealStatus is the status of a retrieval deal returned by a provider in a DealResponse */ declare type DealStatus = number; declare type DealWeight = number; declare class ElectionProof { WinCount: number; VRFProof: []; } declare class ExecutionTrace { Msg: Message; MsgRct: MessageReceipt; Error: string; Duration: number; GasCharges: GasTrace[]; Subcalls: ExecutionTrace[]; } declare type ExitCode = number; declare class Fault { Miner: Address; Epoch: ChainEpoch; } declare class FileRef { Path: string; IsCAR: boolean; } declare class GasTrace { Name: string; Location: Loc[]; TotalGas: number; ComputeGas: number; StorageGas: number; TotalVirtualGas: number; VirtualComputeGas: number; VirtualStorageGas: number; TimeTaken: number; Extra: any; Callers: number[]; } declare class HeadChange { Type: 'current' | string; Val: TipSet; } export declare class HttpJsonRpcConnector extends EventEmitter implements Connector { protected options: string | JsonRpcConnectionOptions; protected reqId: number; url: string; token?: string | undefined; constructor(options: string | JsonRpcConnectionOptions); connect(): Promise<any>; disconnect(): Promise<any>; request(req: RequestArguments): Promise<unknown>; on(event: 'connected' | 'disconnected', listener: (...args: any[]) => void): this; private _headers; } /** * ID is a libp2p peer identity */ declare type ID = string; declare class Import { Key: StoreID; Err: string; Root: Cid; Source: string; FilePath: string; } declare class ImportRes { Root: Cid; ImportID: StoreID; } declare class InvocResult { MsgCid: Cid; Msg: Message; MsgRct: MessageReceipt; GasCost: MsgGasCost; ExecutionTrace: ExecutionTrace; Error: string; Duration: number; } /** * The Auth method group is used to manage the authorization tokens. */ declare class JsonRpcAuthMethodGroup { private conn; constructor(conn: Connector); /** * list the permissions for a given authorization token * @param token */ verify(token: string): Promise<Permission[]>; /** * generate a new authorization token for a given permissions list * @param permissions */ new(permissions: Permission[]): Promise<string>; } /** * The Chain method group contains methods for interacting with the blockchain, but that do not require any form of state computation. */ declare class JsonRpcChainMethodGroup { private conn; constructor(conn: Connector); /** * reads ipld nodes referenced by the specified CID from chain blockstore and returns raw bytes. * @param cid */ readObj(cid: Cid): Promise<string>; /** * deletes node referenced by the given CID * @param cid */ deleteObj(cid: Cid): Promise<string>; /** * returns messages stored in the specified block. * @param blockCid */ getBlockMessages(blockCid: Cid): Promise<BlockMessages>; /** * returns the current head of the chain */ getHead(): Promise<TipSet>; /** * call back on chain head updates. * @param cb * @returns interval id */ chainNotify(cb: (headChange: HeadChange[]) => void): Promise<NodeJS.Timeout | undefined>; stopChainNotify(id?: any): void; /** * returns the block specified by the given CID * @param blockCid */ getBlock(blockCid: Cid): Promise<BlockHeader>; /** * reads a message referenced by the specified CID from the chain blockstore * @param messageCid */ getMessage(messageCid: Cid): Promise<Message>; /** * returns receipts for messages in parent tipset of the specified block * @param blockCid */ getParentReceipts(blockCid: Cid): Promise<MessageReceipt[]>; /** * returns messages stored in parent tipset of the specified block. * @param blockCid */ getParentMessages(blockCid: Cid): Promise<WrappedMessage[]>; /** * checks if a given CID exists in the chain blockstore * @param cid */ hasObj(cid: Cid): Promise<boolean>; /** * returns statistics about the graph referenced by 'obj'. * * @remarks * If 'base' is also specified, then the returned stat will be a diff between the two objects. */ statObj(obj: Cid, base?: Cid): Promise<ObjStat>; /** * Forcefully sets current chain head. Use with caution. * @param tipSetKey */ setHead(tipSetKey: TipSetKey): Promise<void>; /** * Returns the genesis tipset. * @param tipSet */ getGenesis(): Promise<TipSet>; /** * Computes weight for the specified tipset. * @param tipSetKey */ getTipSetWeight(tipSetKey?: TipSetKey): Promise<string>; /** * looks back for a tipset at the specified epoch. * @param epochNumber */ getTipSetByHeight(epochNumber: number): Promise<TipSet>; /** * Returns a set of revert/apply operations needed to get from * @param from * @param to */ getPath(from: TipSetKey, to: TipSetKey): Promise<HeadChange[]>; /** * Returns a stream of bytes with CAR dump of chain data. * @param nroots * @param tipSetKey * * @remarks The exported chain data includes the header chain from the given tipset back to genesis, the entire genesis state, and the most recent 'nroots' state trees. If oldmsgskip is set, messages from before the requested roots are also not included. */ export(nroots: ChainEpoch, oldmsgskip: boolean, tipSetKey: TipSetKey): Promise<any>; } /** * The Client methods all have to do with interacting with the storage and retrieval markets as a client. */ declare class JsonRpcClientMethodGroup { private conn; constructor(conn: Connector); /** * Imports file under the specified path into filestore. * @param fileRef */ import(fileRef: FileRef): Promise<ImportRes>; /** * Removes file import * @param importId */ removeImport(importId: StoreID): Promise<ImportRes>; /** * Proposes a deal with a miner. * @param dealParams */ startDeal(dealParams: StartDealParams): Promise<Cid>; /** * Returns the latest information about a given deal. * @param dealCid */ getDealInfo(dealCid: Cid): Promise<DealInfo>; /** * Returns information about the deals made by the local client. */ listDeals(): Promise<DealInfo[]>; hasLocal(cid: Cid): Promise<boolean>; /** * Identifies peers that have a certain file, and returns QueryOffers (one per peer). * @param cid * @param pieceCid */ findData(cid: Cid, pieceCid?: Cid): Promise<QueryOffer[]>; /** * returns a QueryOffer for the specific miner and file. * @param miner * @param root * @param pieceCid */ minerQueryOffer(miner: Address, root: Cid, pieceCid?: Cid): Promise<QueryOffer>; /** * initiates the retrieval of a file, as specified in the order. * @param order * @param ref */ retrieve(order: RetrievalOrder, ref: FileRef): Promise<void>; /** * returns a signed StorageAsk from the specified miner. * @param peerId * @param miner */ queryAsk(peerId: PeerID, miner: Address): Promise<StorageAsk>; /** * calculates the CommP for a specified file * @param path */ calcCommP(path: string): Promise<CommPRet>; /** * generates a CAR file for the specified file. * @param ref * @param outpath */ genCar(ref: FileRef, outpath: string): Promise<any>; /** * calculates real deal data size * @param root */ dealSize(root: Cid): Promise<DataSize>; /** * returns the status of all ongoing transfers of data */ listDataTransfers(): Promise<DataTransferChannel[]>; /** * attempts to restart stalled retrievals on a given payment channel which are stuck due to insufficient funds. * @param paymentChannel */ retrieveTryRestartInsufficientFunds(paymentChannel: Address): Promise<void>; /** * lists imported files and their root CIDs */ listImports(): Promise<Import[]>; /** * returns the status of updated deals */ getDealUpdates(cb: (data: DealInfo) => void): Promise<void>; /** * initiates the retrieval of a file, as specified in the order, and provides a channel of status updates. * @param order * @param ref * @param cb */ retrieveWithEvents(order: RetrievalOrder, ref: FileRef, cb: (data: RetrievalEvent) => void): Promise<void>; dataTransferUpdates(cb: (data: DataTransferChannel) => void): Promise<void>; /** * returns deal status given a code * @param code */ getDealStatus(code: number): Promise<string>; /** * attempts to restart a data transfer with the given transfer ID and other peer * @param transferId * @param otherPeer * @param isInitiator */ restartDataTransfer(transferId: TransferID, otherPeer: PeerID, isInitiator: boolean): Promise<void>; /** * cancels a data transfer with the given transfer ID and other peer * @param transferId * @param otherPeer * @param isInitiator */ cancelDataTransfer(transferId: TransferID, otherPeer: PeerID, isInitiator: boolean): Promise<void>; dealPieceCID(rootCid: Cid): Promise<DataCIDSize>; } declare class JsonRpcCommonMethodGroup { private conn; constructor(conn: Connector); /** * returns peerID of libp2p node backing this API */ id(): Promise<ID>; /** * provides information about API provider */ version(): Promise<Version>; logList(): Promise<string[]>; logSetLevel(string1: string, string2: string): Promise<any>; /** * trigger graceful shutdown */ shutdown(): Promise<void>; } declare type JsonRpcConnectionOptions = { url: string; token?: string; }; declare class JsonRpcGasMethodGroup { private conn; constructor(conn: Connector); /** * estimate gas fee cap * @param message * @param nblocksincl */ feeCap(message: Message, nblocksincl: number): Promise<string>; /** * estimate gas limit, it fails if message fails to execute. * @param message */ gasLimit(message: Message): Promise<number>; /** * estimate gas to succesufully send message, and have it likely be included in the next nblocksincl blocks * @param nblocksincl * @param sender * @param gasLimit */ gasPremium(nblocksincl: number, sender: string, gasLimit: number): Promise<string>; /** * estimate gas to succesufully send message, and have it included in the next 10 blocks * @param message */ messageGas(message: Message): Promise<Message>; } declare class JsonRpcMinerMethodGroup { private conn; constructor(conn: Connector); /** * MinerGetBaseInfo * @param address * @param chainEpoch * @param tipSetKey */ getBaseInfo(address: string, chainEpoch: ChainEpoch, tipSetKey: TipSetKey): Promise<MiningBaseInfo>; /** * MinerCreateBlock * @param blockTemplate */ createBlock(blockTemplate: BlockTemplate): Promise<BlockMsg>; } /** * The Mpool methods are for interacting with the message pool. The message pool manages all incoming and outgoing 'messages' going over the network. */ declare class JsonRpcMPoolMethodGroup { private conn; constructor(conn: Connector); /** * returns (a copy of) the current mpool config */ getMpoolConfig(): Promise<MpoolConfig>; /** * sets the mpool config to (a copy of) the supplied config * @param config */ setMpoolConfig(config: MpoolConfig): Promise<MpoolConfig>; /** * clears pending messages from the mpool */ clear(): Promise<any>; /** * get all mpool messages * @param tipSetKey */ getMpoolPending(tipSetKey: TipSetKey): Promise<[SignedMessage]>; /** * returns a list of pending messages for inclusion in the next block * @param tipSetKey * @param ticketQuality */ select(tipSetKey: TipSetKey, ticketQuality: number): Promise<[SignedMessage]>; /** * returns a list of pending messages for inclusion in the next block * @param tipSetKey * @param ticketQuality */ sub(cb: (data: MpoolUpdate) => void): Promise<void>; /** * get nonce for address. Note that this method may not be atomic. Use MpoolPushMessage instead. * @param address */ getNonce(address: string): Promise<number>; /** * send message, signed with default lotus wallet * * @remarks * MpoolPushMessage atomically assigns a nonce, signs, and pushes a message * to mempool. * maxFee is only used when GasFeeCap/GasPremium fields aren't specified * When maxFee is set to 0, MpoolPushMessage will guess appropriate fee * based on current chain conditions * @param msg */ pushMessage(msg: Message): Promise<SignedMessage>; /** * send signed message * @param msg */ push(msg: SignedMessage): Promise<Cid>; /** * pushes a signed message to mempool from untrusted sources. * @param message */ pushUntrusted(message: SignedMessage): Promise<Cid>; /** * batch pushes a signed message to mempool. * @param messages */ batchPush(messages: SignedMessage[]): Promise<Cid[]>; /** * batch pushes a signed message to mempool from untrusted sources * @param messages */ batchPushUntrusted(messages: SignedMessage[]): Promise<Cid[]>; /** * batch pushes a unsigned message to mempool * @param messages */ batchPushMessage(messages: Message[]): Promise<SignedMessage[]>; } /** * The Msig methods are used to interact with multisig wallets on the filecoin network */ declare class JsonRpcMsigMethodGroup { private conn; constructor(conn: Connector); /** * returns the portion of a multisig's balance that can be withdrawn or spent * @param address * @param tipSetKey */ getAvailableBalance(address: string, tipSetKey: TipSetKey): Promise<string>; /** * returns the amount of FIL that vested in a multisig in a certain period. * @param address * @param startEpoch * @param endEpoch */ getVested(address: string, startEpoch: TipSetKey, endEpoch: TipSetKey): Promise<string>; /** * creates a multisig wallet * @param requiredNumberOfSenders * @param approvingAddresses * @param unlockDuration * @param initialBalance * @param senderAddressOfCreateMsg * @param gasPrice */ create(requiredNumberOfSenders: number, approvingAddresses: string[], unlockDuration: ChainEpoch, initialBalance: string, senderAddressOfCreateMsg: string, gasPrice: string): Promise<Cid>; /** * proposes a multisig message * @param address * @param recipientAddres * @param value * @param senderAddressOfProposeMsg * @param methodToCallInProposeMsg * @param paramsToIncludeInProposeMsg */ propose(address: string, recipientAddres: string, value: string, senderAddressOfProposeMsg: string, methodToCallInProposeMsg: number, paramsToIncludeInProposeMsg: []): Promise<Cid>; /** * approves a previously-proposed multisig message by transaction ID * @param address * @param proposedTransactionId * @param signerAddress */ approve(address: string, proposedTransactionId: number, signerAddress: string): Promise<Cid>; /** * approves a previously-proposed multisig message * @param address * @param proposedMessageId * @param proposerAddress * @param recipientAddres * @param value * @param senderAddressOfApproveMsg * @param methodToCallInProposeMsg * @param paramsToIncludeInProposeMsg */ approveTxnHash(address: string, proposedMessageId: number, proposerAddress: string, recipientAddres: string, value: string, senderAddressOfApproveMsg: string, methodToCallInProposeMsg: number, paramsToIncludeInProposeMsg: []): Promise<Cid>; /** * cancels a previously-proposed multisig message * @param address * @param proposedMessageId * @param proposerAddress * @param recipientAddres * @param value * @param senderAddressOfCancelMsg * @param methodToCallInProposeMsg * @param paramsToIncludeInProposeMsg */ cancel(address: string, proposedMessageId: number, proposerAddress: string, recipientAddres: string, value: string, senderAddressOfCancelMsg: string, methodToCallInProposeMsg: number, paramsToIncludeInProposeMsg: []): Promise<Cid>; /** * proposes adding a signer in the multisig * @param address * @param senderAddressOfProposeMsg * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ addPropose(address: string, senderAddressOfProposeMsg: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * approves a previously proposed AddSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ addApprove(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * cancels a previously proposed AddSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ addCancel(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * proposes swapping 2 signers in the multisig * @param address * @param senderAddressOfProposeMsg * @param oldSignerAddress * @param newSignerAddress */ swapPropose(address: string, senderAddressOfProposeMsg: string, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * approves a previously proposed SwapSigner * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param oldSignerAddress * @param newSignerAddress */ swapApprove(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * cancels a previously proposed SwapSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param oldSignerAddress * @param newSignerAddress */ swapCancel(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * returns the vesting details of a given multisig. * @param address * @param tipSetKey */ getVestingSchedule(address: string, tipSetKey: TipSetKey): Promise<MsigVesting>; /** * proposes the removal of a signer from the multisig. * @param msigAddress * @param proposerAddress * @param toRemoveAddress * @param decrease * * @remarks It accepts the multisig to make the change on, the proposer address to send the message from, the address to be removed, and a boolean indicating whether or not the signing threshold should be lowered by one along with the address removal. */ removeSigner(msigAddress: Address, proposerAddress: Address, toRemoveAddress: Address, decrease: boolean): Promise<Cid>; } declare class JsonRpcNetMethodGroup { private conn; constructor(conn: Connector); connectedness(peerId: PeerID): Promise<Connectedness>; peers(): Promise<AddrInfo[]>; connect(addrInfo: AddrInfo): Promise<any>; addrsListen(): Promise<AddrInfo>; disconnect(peerID: PeerID): Promise<void>; findPeer(peerID: PeerID): Promise<AddrInfo>; pubsubScores(): Promise<PubsubScore[]>; autoNatStatus(): Promise<NatInfo>; } /** * The Paych methods are for interacting with and managing payment channels */ declare class JsonRpcPaychMethodGroup { private conn; constructor(conn: Connector); /** * PaychGet * @param from * @param to * @param amount */ getPaymentChannel(from: string, to: string, amount: string): Promise<ChannelInfo>; /** * PaychGetWaitReady * @param cid */ getWaitReadyPaymentChannel(cid: Cid): Promise<Address>; /** * PaychList */ getList(): Promise<[Address]>; /** * PaychStatus * @param address */ status(address: string): Promise<PaychStatus>; /** * PaychAllocateLane * @param address */ allocateLane(address: string): Promise<number>; /** * PaychSettle * @param address */ settle(address: string): Promise<Cid>; /** * PaychCollect * @param address */ collect(address: string): Promise<Cid>; /** * PaychAvailableFunds * @param address */ getAvailableFunds(address: string): Promise<ChannelAvailableFunds>; /** * PaychAvailableFundsByFromTo * @param from * @param to */ getAvailableFundsByFromTo(from: string, to: string): Promise<ChannelAvailableFunds>; /** * PaychNewPayment * @param from * @param to * @param vouchers */ newPayment(from: string, to: string, vouchers: [VoucherSpec]): Promise<PaymentInfo>; /** * PaychVoucherCreate * @param address * @param amount * @param lane */ voucherCreate(address: string, amount: string, lane: number): Promise<VoucherCreateResult>; /** * PaychVoucherList * @param address */ voucherList(address: string): Promise<[SignedVoucher]>; /** * PaychVoucherCheckValid * @param address * @param signedVoucher */ voucherCheckValid(address: string, signedVoucher: SignedVoucher): Promise<any>; /** * PaychVoucherAdd * @param address * @param signedVoucher * @param proof * @param minDelta */ voucherAdd(address: string, signedVoucher: SignedVoucher, proof: any, minDelta: string): Promise<string>; /** * PaychVoucherCheckSpendable * @param address * @param signedVoucher * @param secret * @param proof */ voucherCheckSpendable(address: string, signedVoucher: SignedVoucher, secret: any, proof: any): Promise<boolean>; /** * PaychVoucherSubmit * @param address * @param signedVoucher * @param secret * @param proof */ voucherSubmit(address: string, signedVoucher: SignedVoucher, secret: any, proof: any): Promise<Cid>; } /** * The State methods are used to query, inspect, and interact with chain state. * * @remarks * All methods take a TipSetKey as a parameter. The state looked up is the state at that tipset. * If TipSetKey is not provided as a param, the heaviest tipset in the chain to be used. */ declare class JsonRpcStateMethodGroup { private conn; constructor(conn: Connector); /** * runs the given message and returns its result without any persisted changes. */ stateCall(message: Message, tipSetKey?: TipSet): Promise<InvocResult>; /** * replays a given message, assuming it was included in a block in the specified tipset. If no tipset key is provided, the appropriate tipset is looked up. * @param tipSetKey * @param cid */ stateReplay(tipSetKey: TipSetKey, cid: Cid): Promise<InvocResult>; /** * returns the indicated actor's nonce and balance * @param address * @param tipSetKey */ getActor(address: string, tipSetKey?: TipSetKey): Promise<Actor>; /** * returns the indicated actor's state * @param address * @param tipSetKey */ readState(address: string, tipSetKey?: TipSetKey): Promise<ActorState>; /** * looks back and returns all messages with a matching to or from address, stopping at the given height. * @param filter * @param tipSetKey * @param toHeight */ listMessages(match: MessageMatch, tipSetKey?: TipSetKey, toHeight?: number): Promise<Cid[]>; /** * returns the name of the network the node is synced to */ networkName(): Promise<NetworkName>; /** * returns info about the given miner's sectors * @param address * @param tipSetKey */ minerSectors(address: string, tipSetKey?: TipSetKey): Promise<SectorOnChainInfo[]>; /** * returns info about sectors that a given miner is actively proving. * @param address * @param tipSetKey */ minerActiveSectors(address: string, tipSetKey?: TipSetKey): Promise<SectorOnChainInfo[]>; /** * calculates the deadline at some epoch for a proving period and returns the deadline-related calculations. * @param address * @param tipSetKey */ minerProvingDeadline(address: string, tipSetKey?: TipSetKey): Promise<DeadlineInfo>; /** * returns the power of the indicated miner * @param address * @param tipSetKey */ minerPower(address: string, tipSetKey?: TipSetKey): Promise<MinerPower>; /** * returns info about the indicated miner * @param address * @param tipSetKey */ minerInfo(address: string, tipSetKey?: TipSetKey): Promise<MinerInfo>; /** * returns all the proving deadlines for the given miner * @param address * @param tipSetKey */ minerDeadlines(address: string, tipSetKey?: TipSetKey): Promise<Deadline[]>; /** * Loads miner partitions for the specified miner and deadline * @param address * @param idx * @param tipSetKey */ minerPartitions(address: string, idx?: number, tipSetKey?: TipSetKey): Promise<Partition[]>; /** * Returns a bitfield indicating the faulty sectors of the given miner * @param address * @param tipSetKey */ minerFaults(address: string, tipSetKey?: TipSetKey): Promise<BitField>; /** * returns all non-expired Faults that occur within lookback epochs of the given tipset * @param epoch * @param tipSetKey */ allMinerFaults(epoch: ChainEpoch, tipSetKey?: TipSetKey): Promise<Fault[]>; /** * returns a bitfield indicating the recovering sectors of the given miner * @param address * @param tipSetKey */ minerRecoveries(address: string, tipSetKey?: TipSetKey): Promise<BitField>; /** * returns the precommit deposit for the specified miner's sector * @param address * @param sectorPreCommitInfo * @param tipSetKey */ minerPreCommitDepositForPower(address: string, sectorPreCommitInfo: SectorPreCommitInfo, tipSetKey?: TipSetKey): Promise<string>; /** * returns the initial pledge collateral for the specified miner's sector * @param address * @param sectorPreCommitInfo * @param tipSetKey */ minerInitialPledgeCollateral(address: string, sectorPreCommitInfo: SectorPreCommitInfo, tipSetKey?: TipSetKey): Promise<string>; /** * returns the portion of a miner's balance that can be withdrawn or spent * @param address * @param tipSetKey */ minerAvailableBalance(address: string, tipSetKey?: TipSetKey): Promise<string>; /** * returns the PreCommit info for the specified miner's sector * @param address * @param sector * @param tipSetKey */ sectorPreCommitInfo(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorPreCommitOnChainInfo>; /** * StateSectorGetInfo returns the on-chain info for the specified miner's sector * @param address * @param sector * @param tipSetKey * * @remarks * NOTE: returned Expiration may not be accurate in some cases, use StateSectorExpiration to get accurate expiration epoch */ sectorGetInfo(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorOnChainInfo>; /** * returns epoch at which given sector will expire * @param address * @param sector * @param tipSetKey */ sectorExpiration(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorExpiration>; /** * finds deadline/partition with the specified sector * @param address * @param sector * @param tipSetKey */ sectorPartition(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorLocation>; /** * searches for a message in the chain and returns its receipt and the tipset where it was executed * @param cid */ searchMsg(cid: Cid): Promise<MsgLookup>; /** * looks back in the chain for a message. If not found, it blocks until the message arrives on chain, and gets to the indicated confidence depth. * @param cid * @param confidence */ waitMsg(cid: Cid, confidence: number): Promise<MsgLookup>; /** * looks back up to limit epochs in the chain for a message. If not found, it blocks until the message arrives on chain, and gets to the indicated confidence depth. * @param cid * @param confidence * @param limit */ waitMsgLimited(cid: Cid, confidence: number, limit: ChainEpoch): Promise<MsgLookup>; /** * returns the addresses of every miner that has claimed power in the Power Actor * @param tipSetKey */ listMiners(tipSetKey?: TipSetKey): Promise<Address[]>; /** * returns the addresses of every actor in the state * @param tipSetKey */ listActors(tipSetKey?: TipSetKey): Promise<Address[]>; /** * looks up the Escrow and Locked balances of the given address in the Storage Market * @param address * @param tipSetKey */ marketBalance(address: Address, tipSetKey?: TipSetKey): Promise<MarketBalance>; /** * returns the Escrow and Locked balances of every participant in the Storage Market * @param tipSetKey */ marketParticipants(tipSetKey?: TipSetKey): Promise<{ [k: string]: MarketBalance; }>; /** * returns information about every deal in the Storage Market * @param tipSetKey */ marketDeals(tipSetKey?: TipSetKey): Promise<{ [k: string]: MarketDeal; }>; /** * returns information about the indicated deal * @param dealId * @param tipSetKey */ marketStorageDeal(dealId: DealID, tipSetKey?: TipSetKey): Promise<MarketDeal>; /** * retrieves the ID address of the given address * @param address * @param tipSetKey */ lookupId(address: Address, tipSetKey?: TipSetKey): Promise<Address>; /** * returns the public key address of the given ID address * @param address * @param tipSetKey */ accountKey(address: Address, tipSetKey?: TipSetKey): Promise<Address>; /** * returns all the actors whose states change between the two given state CIDs * @param cid1 * @param cid2 */ changedActors(cid1?: Cid, cid2?: Cid): Promise<{ [k: string]: Actor; }>; /** * returns the message receipt for the given message * @param cid * @param tipSetKey */ getReceipt(cid: Cid, tipSetKey?: TipSetKey): Promise<MessageReceipt>; /** * returns the number of sectors in a miner's sector set and proving set * @param address * @param tipSetKey */ minerSectorCount(address: Address, tipSetKey?: TipSetKey): Promise<MinerSectors>; /** * Applies the given messages on the given tipset. * @param epoch * @param messages * @param tipSetKey * * @remarks * The messages are run as though the VM were at the provided height. */ compute(epoch: ChainEpoch, messages: Message[], tipSetKey?: TipSetKey): Promise<ComputeStateOutput>; /** * returns the data cap for the given address. * @param address * @param tipSetKey * * @remarks * Returns nil if there is no entry in the data cap table for the address. */ verifiedClientStatus(address: Address, tipSetKey?: TipSetKey): Promise<StoragePower>; /** * returns the min and max collateral a storage provider can issue * @param size * @param verified * @param tipSetKey */ dealProviderCollateralBounds(size: PaddedPieceSize, verified: boolean, tipSetKey?: TipSetKey): Promise<DealCollateralBounds>; /** * returns the circulating supply of Filecoin at the given tipset * @param tipSetKey */ circulatingSupply(tipSetKey?: TipSetKey): Promise<CirculatingSupply>; /** * returns an approximation of the circulating supply of Filecoin at the given tipset. * * @param tipSetKey * * @remarks This is the value reported by the runtime interface to actors code. */ vmCirculatingSupply(tipSetKey?: TipSetKey): Promise<CirculatingSupply>; /** * returns the data cap for the given address. * @param address * @param tipSetKey */ verifierStatus(address: Address, tipSetKey?: TipSetKey): Promise<StoragePower | null>; /** * returns the network version at the given tipset * @param tipSetKey */ networkVersion(tipSetKey?: TipSetKey): Promise<NetworkVersion>; /** * returns the address of the Verified Registry's root key * @param tipSetKey */ verifiedRegistryRootKey(tipSetKey?: TipSetKey): Promise<Address>; /** * checks if a sector is allocated * @param address * @param sectorNumber * @param tipSetKey */ minerSectorAllocated(address: Address, sectorNumber: SectorNumber, tipSetKey?: TipSetKey): Promise<boolean>; } /** * The Sync method group contains methods for interacting with and observing the lotus sync service. */ declare class JsonRpcSyncMethodGroup { private conn; constructor(conn: Connector); /** * returns the current status of the lotus sync system. */ state(): Promise<SyncState>; /** * checks if a block was marked as bad, and if it was, returns the reason. * @param blockCid */ checkBad(blockCid: Cid): Promise<string>; /** * marks a blocks as bad, meaning that it won't ever by synced. Use with extreme caution. * @param blockCid */ markBad(blockCid: Cid): Promise<void>; /** * purges bad block cache, making it possible to sync to chains previously marked as bad */ unmarkAllBad(): Promise<void>; /** * unmarks a block as bad, making it possible to be validated and synced again. * @param blockCid */ unmarkBad(blockCid: Cid): Promise<void>; /** * marks a blocks as checkpointed, meaning that it won't ever fork away from it. * @param tipSetKey */ checkpoint(tipSetKey: TipSetKey): Promise<string>; /** * can be used to submit a newly created block to the network * @param blockMsg */ submitBlock(blockMsg: BlockMsg): Promise<string>; /** * returns a channel streaming incoming, potentially not yet synced block headers. * @param cb */ incomingBlocks(cb: (blockHeader: BlockHeader) => void): Promise<void>; /** * indicates whether the provided tipset is valid or not * @param tipSetKey */ validateTipset(tipSetKey: TipSetKey): Promise<boolean>; } declare class JsonRpcWalletMethodGroup { private conn; constructor(conn: Connector); /** * creates a new address in the wallet with the given sigType. * @param type */ new(type?: NewAddressType): Promise<string>; /** * get wallet list */ list(): Promise<string[]>; /** * get balance for address * @param address */ balance(address: string): Promise<any>; /** * delete address from lotus * @param address */ delete(address: string): Promise<any>; /** * check if address is in keystore * @param address */ has(address: string): Promise<any>; /** * set default address * @param address */ setDefault(address: string): Promise<undefined>; /** * walletExport returns the private key of an address in the wallet. * @param address */ export(address: string): Promise<KeyInfo>; /** * walletImport returns the private key of an address in the wallet. * @param keyInfo */ import(keyInfo: KeyInfo): Promise<string>; /** * get default address */ getDefaultAddress(): Promise<string>; /** * sign message * @param msg */ signMessage(msg: Message): Promise<SignedMessage>; /** * sign raw message * @param data */ sign(data: string | ArrayBuffer): Promise<Signature>; /** * verify message signature * @param data * @param sign */ verify(address: string, data: string | ArrayBuffer, sign: Signature): Promise<boolean>; /** * validates whether a given string can be decoded as a well-formed address * @param address */ validateAddress(address: string): Promise<Address>; } /** * KeyInfo is used for storing keys in KeyStore */ declare class KeyInfo { Type: string; PrivateKey: []; } declare class Keystore { salt: string; hdPathString: string; encSeed: { encStr: any; nonce: any; } | undefined; version: number; hdIndex: number; encPrivKeys: any; addresses: string[]; private defaultAddressIndex; serialize(): string; deserialize(keystore: string): void; init(mnemonic: string, pwDerivedKey: Uint8Array, hdPathString: string, salt: string): void; createVault(opts: any): Promise<Error | null>; private generateSalt; private isSeedValid; private _encryptString; private _decryptString; private encodeHex; private decodeHex; private _encryptKey; private _decryptKey; private deriveKeyFromPasswordAndSalt; private generateNewAddress; newAddress(n: number, password: string): Promise<void>; deleteAddress(address: string, password: string): Promise<void>; private _generatePrivKeys; getPrivateKey(address: string, password: string): Promise<string>; getDefaultAddress(): Promise<string>; setDefaultAddress(address: string): Promise<void>; getAddresses(): Promise<string[]>; hasAddress(address: string): Promise<boolean>; generateRandomSeed(extraEntropy?: any): string; _concatAndSha256: (entropyBuf0: any, entropyBuf1: any) => Buffer; } export declare class LightWalletProvider extends BaseWalletProvider implements WalletProviderInterface, MultisigProviderInterface { keystore: Keystore; private hdPathString; private signer; private pwdCallback; constructor(client: LotusClient, pwdCallback: Function, path?: string); newAddress(): Promise<string>; deleteAddress(address: string): Promise<void>; hasAddress(address: string): Promise<boolean>; exportPrivateKey(address: string): Promise<KeyInfo>; getAddresses(): Promise<string[]>; getDefaultAddress(): Promise<string>; setDefaultAddress(address: string): Promise<void>; sendMessage(msg: Message): Promise<SignedMessage>; signMessage(msg: Message): Promise<SignedMessage>; sign(data: string | ArrayBuffer): Promise<Signature>; verify(address: string, data: string | ArrayBuffer, sign: Signature): Promise<boolean>; /** * creates a multisig wallet * @param requiredNumberOfSenders * @param approvingAddresses * @param unlockDuration * @param initialBalance * @param senderAddressOfCreateMsg */ msigCreate(requiredNumberOfSenders: number, approvingAddresses: string[], startEpoch: ChainEpoch, unlockDuration: ChainEpoch, initialBalance: string, senderAddressOfCreateMsg: string): Promise<Cid>; /** * proposes a multisig message * @param address * @param recipientAddres * @param value * @param senderAddressOfProposeMsg */ msigProposeTransfer(address: string, recipientAddres: string, value: string, senderAddressOfProposeMsg: string): Promise<Cid>; /** * approves a previously-proposed multisig message by transaction ID * @param address * @param proposedTransactionId * @param signerAddress */ msigApproveTransfer(address: string, proposedTransactionId: number, signerAddress: string): Promise<Cid>; /** * approves a previously-proposed multisig message * @param address * @param proposedMessageId * @param proposerAddress * @param recipientAddres * @param value * @param senderAddressOfApproveMsg */ msigApproveTransferTxHash(address: string, proposedMessageId: number, proposerAddress: string, recipientAddres: string, value: string, senderAddressOfApproveMsg: string): Promise<Cid>; /** * cancels a previously-proposed multisig message * @param address * @param proposedMessageId * @param proposerAddress * @param recipientAddres * @param value * @param senderAddressOfCancelMsg */ msigCancelTransfer(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, recipientAddres: string, value: string): Promise<Cid>; /** * proposes adding a signer in the multisig * @param address * @param senderAddressOfProposeMsg * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ msigProposeAddSigner(address: string, senderAddressOfProposeMsg: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * approves a previously proposed AddSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ msigApproveAddSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * cancels a previously proposed AddSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ msigCancelAddSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * proposes swapping 2 signers in the multisig * @param address * @param senderAddressOfProposeMsg * @param oldSignerAddress * @param newSignerAddress */ msigProposeSwapSigner(address: string, senderAddressOfProposeMsg: string, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * approves a previously proposed SwapSigner * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param oldSignerAddress * @param newSignerAddress */ msigApproveSwapSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * cancels a previously proposed SwapSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param oldSignerAddress * @param newSignerAddress */ msigCancelSwapSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * proposes removing a signer from the multisig * @param address * @param senderAddressOfProposeMsg * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ msigProposeRemoveSigner(address: string, senderAddressOfProposeMsg: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * approves a previously proposed RemoveSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ msigApproveRemoveSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * cancels a previously proposed RemoveSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ msigCancelRemoveSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; createLightWallet(password: string): Promise<string>; recoverLightWallet(mnemonic: string, password: string): Promise<void>; loadLightWallet(encryptedWallet: string): void; prepareToSave(): string; getSigner(): LightWalletSigner; } export declare class LightWalletSigner implements Signer { private keystore; constructor(keystore: Keystore); sign(message: Message, password?: string): Promise<SignedMessage>; private messageToSigner; } declare class Loc { File: string; Line: number; Function: string; } export declare class LotusClient { conn: Connector; chain: JsonRpcChainMethodGroup; state: JsonRpcStateMethodGroup; auth: JsonRpcAuthMethodGroup; client: JsonRpcClientMethodGroup; common: JsonRpcCommonMethodGroup; miner: JsonRpcMinerMethodGroup; paych: JsonRpcPaychMethodGroup; mpool: JsonRpcMPoolMethodGroup; net: JsonRpcNetMethodGroup; msig: JsonRpcMsigMethodGroup; sync: JsonRpcSyncMethodGroup; gasEstimate: JsonRpcGasMethodGroup; wallet: JsonRpcWalletMethodGroup; constructor(connector: Connector); release(): Promise<any>; } export declare class LotusWalletProvider extends BaseWalletProvider implements WalletProviderInterface, MultisigProviderInterface { constructor(client: LotusClient); /** * create new wallet * @param type */ newAddress(type?: NewAddressType): Promise<string>; /** * delete address from lotus * @param address */ deleteAddress(address: string): Promise<any>; /** * get wallet list */ getAddresses(): Promise<string[]>; /** * check if address is in keystore * @param address */ hasAddress(address: string): Promise<boolean>; /** * set default address * @param address */ setDefaultAddress(address: string): Promise<undefined>; /** * get default address */ getDefaultAddress(): Promise<string>; /** * walletExport returns the private key of an address in the wallet. * @param address */ exportPrivateKey(address: string): Promise<KeyInfo>; /** * send message, signed with default lotus wallet * @param msg */ sendMessage(msg: Message): Promise<SignedMessage>; /** * sign message * @param msg */ signMessage(msg: Message): Promise<SignedMessage>; /** * sign raw message * @param data */ sign(data: string | ArrayBuffer): Promise<Signature>; /** * verify message signature * @param data * @param sign */ verify(address: string, data: string | ArrayBuffer, sign: Signature): Promise<boolean>; /** * creates a multisig wallet * @param requiredNumberOfSenders * @param approvingAddresses * @param startEpoch * @param unlockDuration * @param initialBalance * @param senderAddressOfCreateMsg */ msigCreate(requiredNumberOfSenders: number, approvingAddresses: string[], startEpoch: ChainEpoch, unlockDuration: ChainEpoch, initialBalance: string, senderAddressOfCreateMsg: string): Promise<Cid>; /** * proposes a multisig message * @param address * @param recipientAddres * @param value * @param senderAddressOfProposeMsg */ msigProposeTransfer(address: string, recipientAddres: string, value: string, senderAddressOfProposeMsg: string): Promise<Cid>; /** * approves a previously-proposed multisig message by transaction ID * @param address * @param proposedTransactionId * @param signerAddress */ msigApproveTransfer(address: string, proposedTransactionId: number, signerAddress: string): Promise<Cid>; /** * approves a previously-proposed multisig message * @param address * @param proposedMessageId * @param proposerAddress * @param recipientAddres * @param value * @param senderAddressOfApproveMsg */ msigApproveTransferTxHash(address: string, proposedMessageId: number, proposerAddress: string, recipientAddres: string, value: string, senderAddressOfApproveMsg: string): Promise<Cid>; /** * cancels a previously-proposed multisig message * @param address * @param proposedMessageId * @param proposerAddress * @param recipientAddres * @param value * @param senderAddressOfCancelMsg */ msigCancelTransfer(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, recipientAddres: string, value: string): Promise<Cid>; /** * proposes adding a signer in the multisig * @param address * @param senderAddressOfProposeMsg * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ msigProposeAddSigner(address: string, senderAddressOfProposeMsg: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * approves a previously proposed AddSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ msigApproveAddSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * cancels a previously proposed AddSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ msigCancelAddSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * proposes swapping 2 signers in the multisig * @param address * @param senderAddressOfProposeMsg * @param oldSignerAddress * @param newSignerAddress */ msigProposeSwapSigner(address: string, senderAddressOfProposeMsg: string, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * approves a previously proposed SwapSigner * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param oldSignerAddress * @param newSignerAddress */ msigApproveSwapSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * cancels a previously proposed SwapSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param oldSignerAddress * @param newSignerAddress */ msigCancelSwapSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * proposes removing a signer from the multisig * @param address * @param senderAddressOfProposeMsg * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ msigProposeRemoveSigner(address: string, senderAddressOfProposeMsg: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * approves a previously proposed RemoveSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ msigApproveRemoveSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * cancels a previously proposed RemoveSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ msigCancelRemoveSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * walletImport returns the private key of an address in the wallet. * @param keyInfo */ walletImport(keyInfo: KeyInfo): Promise<string>; } declare class MarketBalance { Escrow: string; Locked: string; } declare class MarketDeal { Proposal: DealProposal; State: DealState; } declare class Merge { Lane: number; Nonce: number; } declare class Message { Version?: number; To: string; From: string; Nonce: number; Value: BigNumber; GasLimit: number; GasFeeCap: BigNumber; GasPremium: BigNumber; Method: number; Params: string; } declare class MessageMatch { To?: Address; From?: Address; } declare class MessagePartial { Version?: number; To: string; From: string; Nonce?: number; Value?: BigNumber; GasLimit?: number; GasFeeCap?: BigNumber; GasPremium?: BigNumber; Method?: number; Params?: string; } declare class MessageReceipt { ExitCode: ExitCode; Return: any; GasUsed: number; } export declare class MetamaskSigner implements Signer { private filecoinApi; constructor(filecoinApi: FilecoinSnapApi); sign(message: Message): Promise<SignedMessage>; getDefaultAccount(): Promise<string>; private messageToSigner; private messageFromSigner; } export declare class MetamaskSnapHelper { private connection; private isInstalled; private snap; filecoinApi: FilecoinSnapApi | undefined; error: string | undefined; constructor(connection: JsonRpcConnectionOptions); installFilecoinSnap(): Promise<any>; } export declare class MetamaskWalletProvider extends BaseWalletProvider implements WalletProviderInterface { private signer; constructor(client: LotusClient, filecoinApi: FilecoinSnapApi); newAddress(): Promise<string>; deleteAddress(address: string): Promise<any>; hasAddress(address: string): Promise<any>; exportPrivateKey(address: string): Promise<KeyInfo>; getAddresses(): Promise<string[]>; getDefaultAddress(): Promise<string>; setDefaultAddress(address: string): Promise<undefined>; sendMessage(msg: Message): Promise<SignedMessage>; signMessage(msg: Message): Promise<SignedMessage>; sign(data: string | ArrayBuffer): Promise<Signature>; verify(address: string, data: string | ArrayBuffer, sign: Signature): Promise<boolean>; getSigner(): MetamaskSigner; } declare class MinerInfo { /** * Account that owns the miner. * * @remarks * Income and returned collateral are paid to this address. This address is also allowed to change the worker address for the miner. */ Owner: Address; /** * Worker account for the miner. * * @remarks * The associated pubkey-type address is used to sign blocks and messages on behalf of this miner. */ Worker: Address; /** * Additional addresses that are permitted to submit messages controlling this actor */ ControlAddresses?: Address[]; PendingWorkerKey: WorkerKeyChange; /** * Libp2p identity that should be used when connecting to this miner. */ PeerId: PeerID; /** * Libp2p multi-addresses used for establishing a connection with this miner. */ Multiaddrs: Multiaddrs[] | null; /** * The proof type used by this miner for sealing sectors. */ SealProofType: RegisteredSealProof; /** * Amount of space in each sector committed by this miner. * * @remarks * This is computed from the proof type and represented here redundantly. */ SectorSize: SectorSize; /** * The number of sectors in each Window PoSt partition (proof). * * @remarks * This is computed from the proof type and represented here redundantly. */ WindowPoStPartitionSectors: number; /** * The next epoch this miner is eligible for certain permissioned actor methods and winning block elections as a result of being reported for a consensus fault. */ ConsensusFaultElapsed: ChainEpoch; } declare class MinerPower { MinerPower: Claim; TotalPower: Claim; HasMinPower: boolean; } declare class MinerSectors { /** * Sectors actively contributing to power. */ Active: number; /** * Sectors with failed proofs. */ Faulty: number; /** * Live sectors that should be proven. */ Live: number; } declare class MiningBaseInfo { MinerPower: string; NetworkPower: string; Sectors: SectorInfo[]; WorkerKey: Address; SectorSize: number; PrevBeaconEntry: BeaconEntry; BeaconEntries: BeaconEntry[]; EligibleForMining: boolean; } export declare class MnemonicSigner implements Signer { private mnemonic; private password; private privKeys; addresses: string[]; private defaultAddressIndex; private hdIndex; private path; constructor(mnemonic: string | StringGetter, password: string | StringGetter, path?: string); initAddresses(): Promise<void>; getAddresses(): Promise<string[]>; newAddress(n: number): Promise<void>; deleteAddress(address: string): Promise<void>; getPrivateKey(address: string): Promise<any>; getDefaultAddress(): Promise<string>; setDefaultAddress(address: string): Promise<void>; hasAddress(address: string): Promise<boolean>; sign(message: Message): Promise<SignedMessage>; private getPassword; private getMnemonic; private messageToSigner; } export declare class MnemonicWalletProvider extends BaseWalletProvider implements WalletProviderInterface, MultisigProviderInterface { private signer; constructor(client: LotusClient, mnemonic: string | StringGetter, path?: string); newAddress(): Promise<string>; deleteAddress(address: string): Promise<any>; hasAddress(address: string): Promise<boolean>; exportPrivateKey(address: string): Promise<KeyInfo>; getAddresses(): Promise<string[]>; getDefaultAddress(): Promise<string>; setDefaultAddress(address: string): Promise<void>; sendMessage(msg: Message): Promise<SignedMessage>; signMessage(msg: Message): Promise<SignedMessage>; sign(data: string | ArrayBuffer): Promise<Signature>; verify(address: string, data: string | ArrayBuffer, sign: Signature): Promise<boolean>; getSigner(): MnemonicSigner; /** * creates a multisig wallet * @param requiredNumberOfSenders * @param approvingAddresses * @param startEpoch * @param unlockDuration * @param initialBalance * @param senderAddressOfCreateMsg */ msigCreate(requiredNumberOfSenders: number, approvingAddresses: string[], startEpoch: ChainEpoch, unlockDuration: ChainEpoch, initialBalance: string, senderAddressOfCreateMsg: string): Promise<Cid>; /** * proposes a multisig message * @param address * @param recipientAddres * @param value * @param senderAddressOfProposeMsg */ msigProposeTransfer(address: string, recipientAddres: string, value: string, senderAddressOfProposeMsg: string): Promise<Cid>; /** * approves a previously-proposed multisig message by transaction ID * @param address * @param proposedTransactionId * @param signerAddress */ msigApproveTransfer(address: string, proposedTransactionId: number, signerAddress: string): Promise<Cid>; /** * approves a previously-proposed multisig message * @param address * @param proposedMessageId * @param proposerAddress * @param recipientAddres * @param value * @param senderAddressOfApproveMsg */ msigApproveTransferTxHash(address: string, proposedMessageId: number, proposerAddress: string, recipientAddres: string, value: string, senderAddressOfApproveMsg: string): Promise<Cid>; /** * cancels a previously-proposed multisig message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param recipientAddres * @param value */ msigCancelTransfer(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, recipientAddres: string, value: string): Promise<Cid>; /** * proposes adding a signer in the multisig * @param address * @param senderAddressOfProposeMsg * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ msigProposeAddSigner(address: string, senderAddressOfProposeMsg: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * approves a previously proposed AddSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ msigApproveAddSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * cancels a previously proposed AddSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ msigCancelAddSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * proposes swapping 2 signers in the multisig * @param address * @param senderAddressOfProposeMsg * @param oldSignerAddress * @param newSignerAddress */ msigProposeSwapSigner(address: string, senderAddressOfProposeMsg: string, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * approves a previously proposed SwapSigner * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param oldSignerAddress * @param newSignerAddress */ msigApproveSwapSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * cancels a previously proposed SwapSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param oldSignerAddress * @param newSignerAddress */ msigCancelSwapSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; /** * proposes removing a signer from the multisig * @param address * @param senderAddressOfProposeMsg * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ msigProposeRemoveSigner(address: string, senderAddressOfProposeMsg: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * approves a previously proposed RemoveSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ msigApproveRemoveSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; /** * cancels a previously proposed RemoveSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ msigCancelRemoveSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; } declare class ModVerifyParams { Actor: string; Method: number; Data: []; } declare class MpoolConfig { PriorityAddrs: Address[]; SizeLimitHigh: number; SizeLimitLow: number; ReplaceByFeeRatio: number; PruneCooldown: number; GasLimitOverestimation: number; } declare class MpoolUpdate { Type: number; Message: SignedMessage; } declare class MsgGasCost { Message: Cid; GasUsed: TokenAmount; BaseFeeBurn: TokenAmount; OverEstimationBurn: TokenAmount; MinerPenalty: TokenAmount; MinerTip: TokenAmount; Refund: TokenAmount; TotalCost: TokenAmount; } declare class MsgLookup { /** * @remarks * Can be different than requested, in case it was replaced, but only gas values changed */ Message: Cid; Receipt: MessageReceipt; ReturnDec: any; TipSet: TipSetKey; Height: ChainEpoch; } declare class MsigVesting { InitialBalance: TokenAmount; StartEpoch: ChainEpoch; UnlockDuration: ChainEpoch; } /** * multiaddr is the data type representing a Multiaddr */ declare type Multiaddr = string; declare type Multiaddrs = any; declare interface MultisigProviderInterface { msigCreate(requiredNumberOfSenders: number, approvingAddresses: string[], startEpoch: ChainEpoch, unlockDuration: ChainEpoch, initialBalance: string, senderAddressOfCreateMsg: string): Promise<Cid>; msigProposeTransfer(address: string, recipientAddres: string, value: string, senderAddressOfProposeMsg: string): Promise<Cid>; msigApproveTransfer(address: string, proposedTransactionId: number, signerAddress: string): Promise<Cid>; msigApproveTransferTxHash(address: string, proposedMessageId: number, proposerAddress: string, recipientAddres: string, value: string, senderAddressOfApproveMsg: string): Promise<Cid>; msigCancelTransfer(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, recipientAddres: string, value: string, methodToCallInProposeMsg: number): Promise<Cid>; msigProposeAddSigner(address: string, senderAddressOfProposeMsg: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; msigApproveAddSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; msigCancelAddSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean): Promise<Cid>; msigProposeSwapSigner(address: string, senderAddressOfProposeMsg: string, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; msigApproveSwapSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; msigCancelSwapSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, oldSignerAddress: string, newSignerAddress: string): Promise<Cid>; msigProposeRemoveSigner(address: string, senderAddressOfProposeMsg: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; msigApproveRemoveSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; msigCancelRemoveSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid>; } declare class NatInfo { Reachability: Reachability; PublicAddr: string; } declare type NetworkName = string; declare type NetworkVersion = number; declare enum NewAddressType { BLS = "bls", SECP256K1 = "secp256k1", SECP256K1_LEDGER = "secp256k1-ledger" } declare class ObjStat { Size: number; Links: number; } declare type PaddedPieceSize = number; declare class Partition { /** * Sector numbers in this partition, including faulty, unproven, and terminated sectors. */ AllSectors: BitField; /** * Subset of sectors detected/declared faulty and not yet recovered (excl. from PoSt). */ FaultySectors: BitField; /** * Subset of faulty sectors expected to recover on next PoSt */ RecoveringSectors: BitField; ActiveSectors: BitField; LiveSectors: BitField; } declare class PaychStatus { ControlAddr: Address; Direction: number; } declare class PaymentInfo { Channel: string; WaitSentinel: Cid; Vouchers: SignedVoucher[]; } declare type PeerID = string; declare type Permission = string; declare class PoStProof { PoStProof: number; ProofBytes: []; } declare class PowerPair { Raw: StoragePower; QA: StoragePower; } declare class PubsubScore { ID: ID; Score: Score; } declare class QueryOffer { Err: string; Root: Cid; Piece: Cid; Size: number; MinPrice: string; UnsealPrice: string; PaymentInterval: number; PaymentIntervalIncrease: number; Miner: Address; MinerPeer: RetrievalPeer; } /** * Reachability indicates how reachable a node is./** */ declare type Reachability = number; declare type RegisteredProof = number; declare type RegisteredSealProof = RegisteredProof; declare interface RequestArguments { readonly method: string; readonly params?: readonly unknown[]; } declare class RetrievalEvent { Event: ClientEvent; Status: DealStatus; BytesReceived: number; FundsSpent: TokenAmount; Err: string; } declare class RetrievalOrder { Root: Cid; Piece?: Cid; Size: number; Total: string; UnsealPrice: string; PaymentInterval: number; PaymentIntervalIncrease: number; Client: Address; Miner: Address; MinerPeer: RetrievalPeer; } /** * RetrievalPeer is a provider address/peer.ID pair (everything needed to make deals for with a miner) */ declare class RetrievalPeer { Address: Address; ID?: ID; PieceCID?: Cid; } declare class Score { Score: number; Topics: any; AppSpecificScore: number; IPColocationFactor: number; BehaviourPenalty: number; } declare class SectorExpiration { OnTime: ChainEpoch; /** * non-zero if sector is faulty, epoch at which it will be permanently removed if it doesn't recover */ Early: ChainEpoch; } declare class SectorInfo { SealProof: number; SectorNumber: number; SealedCID: Cid; } declare class SectorLocation { Deadline: number; Partition: number; } declare type SectorNumber = number; /** * Information stored on-chain for a proven sector. */ declare class SectorOnChainInfo { SectorNumber: SectorNumber; /** * The seal proof type implies the PoSt proof/s */ SealProof: RegisteredSealProof; /** * CommR */ SealedCID: Cid; DealIDs: DealID[]; /** * Epoch during which the sector proof was accepted */ Activation: ChainEpoch; /** * Epoch during which the sector expires */ Expiration: ChainEpoch; /** * Integral of active deals over sector lifetime */ DealWeight: DealWeight; /** * Integral of active verified deals over sector lifetime */ VerifiedDealWeight: DealWeight; /** * Pledge collected to commit this sector */ InitialPledge: TokenAmount; /** * Expected one day projection of reward for sector computed at activation time */ ExpectedDayReward: TokenAmount; /** * Expected twenty day projection of reward for sector computed at activation time */ ExpectedStoragePledge: TokenAmount; /** * Age of sector this sector replaced or zero */ ReplacedSectorAge: ChainEpoch; /** * Day reward of sector this sector replace or zero */ ReplacedDayReward: TokenAmount; } declare class SectorPreCommitInfo { SealProof: RegisteredSealProof; SectorNumber: SectorNumber; /** * CommR */ SealedCID: Cid; SealRandEpoch: ChainEpoch; DealIDs: DealID | null; Expiration: ChainEpoch; /** * Whether to replace a "committed capacity" no-deal sector * * @remarks * It requires non-empty DealIDs */ ReplaceCapacity: boolean; /** * The committed capacity sector to replace, and it's deadline/partition location */ ReplaceSectorDeadline: number; ReplaceSectorPartition: number; ReplaceSectorNumber: SectorNumber; } /** * Information stored on-chain for a pre-committed sector. */ declare class SectorPreCommitOnChainInfo { Info: SectorPreCommitInfo; PreCommitDeposit: TokenAmount; PreCommitEpoch: ChainEpoch; /** * Integral of active deals over sector lifetime */ DealWeight: DealWeight; /** * Integral of active verified deals over sector lifetime */ VerifiedDealWeight: DealWeight; } /** * It indicates one of a set of possible sizes in the network. * * @remarks * 1KiB = 1024 * 1MiB = 1048576 * 1GiB = 1073741824 * 1TiB = 1099511627776 * 1PiB = 1125899906842624 * 1EiB = 1152921504606846976 * max = 18446744073709551615 */ declare type SectorSize = number; declare interface Signature { Data: string; Type: number; } declare interface SignedMessage { Message: Message; Signature: Signature; } /** * A voucher is sent by `From` to `To` off-chain in order to enable * `To` to redeem payments on-chain in the future */ declare class SignedVoucher { /** * Address of the payment channel this signed voucher is valid for */ ChannelAddr: string; /** * Min epoch before which the voucher cannot be redeemed */ TimeLockMin: ChainEpoch; /** * Max epoch beyond which the voucher cannot be redeemed * TimeLockMax set to 0 means no timeout */ TimeLockMax: ChainEpoch; /** * (optional) The SecretPreImage is used by `To` to validate */ SecretPreimage?: []; /** * (optional) Extra can be specified by `From` to add a verification method to the voucher */ Extra?: ModVerifyParams; /** * Specifies which lane the Voucher merges into (will be created if does not exist) */ Lane: number; /** * Nonce is set by `From` to prevent redemption of stale vouchers on a lane */ Nonce: number; /** * Amount voucher can be redeemed for */ Amount: string; /** * (optional) MinSettleHeight can extend channel MinSettleHeight if needed */ MinSettleHeight?: ChainEpoch; /** * (optional) Set of lanes to be merged into `Lane` */ Merges?: Merge[]; /** * Sender's signature over the voucher */ Signature: Signature; } declare interface Signer { sign(message: Message, password?: string): Promise<SignedMessage | undefined>; } declare class StartDealParams { Data: DataRef; Wallet: Address; Miner: Address; EpochPrice: string; MinBlocksDuration: number; ProviderCollateral?: string; DealStartEpoch?: ChainEpoch; FastRetrieval?: boolean; VerifiedDeal?: boolean; } /** * StorageAsk defines the parameters by which a miner will choose to accept or reject a deal. * * @remarks making a storage deal proposal which matches the miner's ask is a precondition, but not sufficient to ensure the deal is accepted (the storage provider may run its own decision logic). */ declare class StorageAsk { /** * Price per GiB / Epoch */ Price: TokenAmount; VerifiedPrice: TokenAmount; MinPieceSize: PaddedPieceSize; MaxPieceSize: PaddedPieceSize; Miner: Address; Timestamp: ChainEpoch; Expiry: ChainEpoch; SeqNo: number; } /** * StorageDealStatus is the local status of a StorageDeal. * * @remarks This status has meaning in the context of this module only - it is not recorded on chain */ declare type StorageDealStatus = number; /** * The unit of storage power (measured in bytes) */ declare type StoragePower = string; declare type StoreID = number; declare type StringGetter = () => Promise<string>; declare type SubscriptionId = string; declare class SyncState { ActiveSyncs: ActiveSync[]; VMApplied: number; } declare type SyncStateStage = number; declare class Ticket { VRFProof: []; } declare class TipSet { Cids: Cid[]; Blocks: BlockHeader[]; Height: number; } declare type TipSetKey = Cid[]; declare type TokenAmount = string; /** * TransferID is an identifier for a data transfer, shared between request/responder and unique to the requester. */ declare type TransferID = number; declare type UnpaddedPieceSize = number; declare class Version { Version: string; APIVersion: number; BlockDelay: number; } /** * VoucherCreateResult is the response to calling PaychVoucherCreate */ declare class VoucherCreateResult { /** * Voucher that was created, or nil if there was an error or if there were insufficient funds in the channel */ Voucher: SignedVoucher; /** * Additional amount that would be needed in the channel in order to be able to create the voucher */ Shortfall: string; } declare class VoucherSpec { Amount: string; TimeLockMin: ChainEpoch; TimeLockMax: ChainEpoch; MinSettle: ChainEpoch; Extra: ModVerifyParams; } declare interface WalletProviderInterface { newAddress(): Promise<string>; deleteAddress(address: string): Promise<void>; getAddresses(): Promise<string[]>; hasAddress(address: string): Promise<any>; setDefaultAddress(address: string): Promise<void>; getDefaultAddress(): Promise<string>; exportPrivateKey(address: string): Promise<KeyInfo>; sendMessage(msg: Message): Promise<SignedMessage>; signMessage(msg: Message): Promise<SignedMessage>; sign(data: string): Promise<Signature>; verify(address: string, data: string | ArrayBuffer, sign: Signature): Promise<boolean>; } declare type WebSocketConnectionOptions = { url: string; token?: string; }; declare class WorkerKeyChange { NewWorker: Address; EffectiveAt: ChainEpoch; } declare class WrappedMessage { Cid: Cid; Message: Message; } export declare class WsJsonRpcConnector extends EventEmitter implements Connector { url: string; token?: string; private websocket; private requests; private websocketReady; constructor(options: WebSocketConnectionOptions); connect(): Promise<any>; request(args: RequestArguments): Promise<any>; closeSubscription(subscriptionId: string): Promise<void>; disconnect(): Promise<any>; private fullUrl; on(event: 'connected' | 'disconnected' | 'error' | SubscriptionId, listener: (...args: any[]) => void): this; private onSocketClose; private onSocketError; private onSocketOpen; private onSocketMessage; } export { }
the_stack
import AudioTrackController from '../../../src/controller/audio-track-controller'; import Hls, { MediaPlaylist } from '../../../src/hls'; import { AttrList } from '../../../src/utils/attr-list'; import { LevelDetails } from '../../../src/loader/level-details'; import { Events } from '../../../src/events'; import * as sinon from 'sinon'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { PlaylistContextType } from '../../../src/types/loader'; chai.use(sinonChai); const expect = chai.expect; describe('AudioTrackController', function () { const tracks: MediaPlaylist[] = [ { attrs: new AttrList({}), bitrate: 0, autoselect: false, default: true, forced: false, groupId: '1', id: 0, name: 'A', type: 'AUDIO', url: '', }, { attrs: new AttrList({}), bitrate: 0, autoselect: false, default: false, forced: false, groupId: '1', id: 1, name: 'B', type: 'AUDIO', url: '', }, { attrs: new AttrList({}), bitrate: 0, autoselect: false, default: false, forced: false, groupId: '1', id: 2, name: 'C', type: 'AUDIO', url: '', }, { attrs: new AttrList({}), bitrate: 0, autoselect: false, default: true, forced: false, groupId: '2', id: 0, name: 'A', type: 'AUDIO', url: '', }, { attrs: new AttrList({}), bitrate: 0, autoselect: false, default: false, forced: false, groupId: '2', id: 1, name: 'B', type: 'AUDIO', url: '', }, { attrs: new AttrList({}), bitrate: 0, autoselect: false, default: false, forced: false, groupId: '2', id: 2, name: 'C', type: 'AUDIO', url: '', }, ]; let hls; //: Hls; let audioTrackController; //: AudioTrackController; const levels = [ { urlId: 1, audioGroupIds: ['1', '2'], }, ]; beforeEach(function () { hls = new Hls(); audioTrackController = new AudioTrackController(hls); hls.levelController = { levels, }; }); afterEach(function () { hls.destroy(); }); describe('onManifestLoading', function () { it('should reset the tracks list and current trackId', function () { audioTrackController.tracks = tracks; audioTrackController.onManifestLoading(); expect(audioTrackController.tracks).to.be.empty; }); }); describe('onLevelLoading', function () { it('should set the audioTracks contained in the event data and trigger AUDIO_TRACKS_UPDATED', function () { const audioTracksUpdatedCallback = sinon.spy(); hls.on(Hls.Events.AUDIO_TRACKS_UPDATED, audioTracksUpdatedCallback); audioTrackController.onManifestParsed(Events.MANIFEST_PARSED, { audioTracks: tracks, }); audioTrackController.onLevelLoading(Events.LEVEL_LOADING, { level: 0, }); expect(audioTrackController.tracks).to.equal(tracks); expect(audioTracksUpdatedCallback).to.be.calledOnce; expect(audioTracksUpdatedCallback).to.be.calledWith( Events.AUDIO_TRACKS_UPDATED, { audioTracks: tracks.slice(3, 6), } ); }); }); it('should select audioGroupId and trigger AUDIO_TRACK_SWITCHING', function (done) { hls.on(Hls.Events.AUDIO_TRACK_SWITCHING, (event, data) => { done(); }); const newLevelInfo = levels[0]; const newGroupId = newLevelInfo.audioGroupIds[newLevelInfo.urlId]; audioTrackController.tracks = tracks; // Update the level to set audioGroupId audioTrackController.onLevelLoading(Events.LEVEL_LOADING, { level: 0, }); audioTrackController.audioTrack = 2; // current track name const audioTrackName = tracks[audioTrackController.audioTrack].name; audioTrackController.onManifestParsed(Events.MANIFEST_PARSED, { audioTracks: tracks, }); // group has switched expect(audioTrackController.groupId).to.equal(newGroupId); // name is still the same expect(tracks[audioTrackController.audioTrack].name).to.equal( audioTrackName ); }); it('should always switch tracks when audioTrack is set to a valid index', function () { const audioTracksUpdatedCallback = sinon.spy(); const audioTrackSwitchingCallback = sinon.spy(); hls.on(Hls.Events.AUDIO_TRACKS_UPDATED, audioTracksUpdatedCallback); hls.on(Hls.Events.AUDIO_TRACK_SWITCHING, audioTrackSwitchingCallback); audioTrackController.onManifestParsed(Events.MANIFEST_PARSED, { audioTracks: tracks, }); audioTrackController.onLevelLoading(Events.LEVEL_LOADING, { level: 0, }); expect(audioTracksUpdatedCallback, 'AUDIO_TRACKS_UPDATED').to.have.been .calledOnce; expect( audioTrackSwitchingCallback, 'AUDIO_TRACK_SWITCHING to initial track 0' ).to.have.been.calledOnce; audioTrackController.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED, { details: new LevelDetails(''), id: 0, groupId: '1', networkDetails: null, stats: { loading: {} }, deliveryDirectives: null, }); expect(audioTrackController.tracksInGroup[0], 'tracksInGroup[0]') .to.have.property('details') .which.is.an('object'); audioTrackController.audioTrack = 1; expect(audioTrackSwitchingCallback, 'AUDIO_TRACK_SWITCHING to track 1').to .have.been.calledTwice; audioTrackController.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED, { details: new LevelDetails(''), id: 1, groupId: '1', networkDetails: null, stats: { loading: {} }, deliveryDirectives: null, }); expect(audioTrackController.tracksInGroup[1], 'tracksInGroup[1]') .to.have.property('details') .which.is.an('object'); audioTrackController.audioTrack = 0; expect(audioTrackSwitchingCallback, 'AUDIO_TRACK_SWITCHING back to track 0') .to.have.been.calledThrice; }); describe('shouldLoadTrack', function () { it('should not need loading because the audioTrack is embedded in the main playlist', function () { audioTrackController.canLoad = true; expect(audioTrackController.shouldLoadTrack({ details: { live: true } })) .to.be.false; expect(audioTrackController.shouldLoadTrack({ details: undefined })).to.be .false; }); it('should need loading because the track has not been loaded yet', function () { audioTrackController.canLoad = true; expect( audioTrackController.shouldLoadTrack({ details: { live: true }, url: 'http://example.com/manifest.m3u8', }), 'track 1' ).to.be.true; expect( audioTrackController.shouldLoadTrack({ details: null, url: 'http://example.com/manifest.m3u8', }), 'track 2' ).to.be.true; }); }); describe('onLevelLoading', function () { it('should reselect the current track and trigger AUDIO_TRACK_SWITCHING eventually', function (done) { hls.on(Hls.Events.AUDIO_TRACK_SWITCHING, (event, data) => { done(); }); const levelLoadedEvent = { level: 0, }; const newLevelInfo = levels[levelLoadedEvent.level]; const newGroupId = newLevelInfo.audioGroupIds[newLevelInfo.urlId]; audioTrackController.tracks = tracks; audioTrackController.onLevelLoading(Events.LEVEL_LOADING, { level: 0, }); audioTrackController.audioTrack = 2; // current track name const audioTrackName = tracks[audioTrackController.audioTrack].name; audioTrackController.onLevelLoading( Events.LEVEL_LOADING, levelLoadedEvent ); // group has switched expect(audioTrackController.groupId).to.equal(newGroupId); // name is still the same expect(tracks[audioTrackController.audioTrack].name).to.equal( audioTrackName ); }); it('should load audio tracks with a url', function () { const shouldLoadTrack = sinon.spy( audioTrackController, 'shouldLoadTrack' ); const audioTrackLoadingCallback = sinon.spy(); const trackWithUrl = { groupId: '1', id: 0, name: 'A', default: true, url: './trackA.m3u8', }; hls.on(Hls.Events.AUDIO_TRACK_LOADING, audioTrackLoadingCallback); hls.levelController = { levels: [ { urlId: 0, audioGroupIds: ['1'], }, ], }; audioTrackController.tracks = [trackWithUrl]; audioTrackController.onLevelLoading(Events.LEVEL_LOADING, { level: 0, }); audioTrackController.startLoad(); expect(shouldLoadTrack).to.have.been.calledTwice; expect(shouldLoadTrack).to.have.been.calledWith(trackWithUrl); expect( shouldLoadTrack.firstCall.returnValue, 'expected shouldLoadTrack to return false before startLoad() is called' ).to.be.false; expect( shouldLoadTrack.secondCall.returnValue, 'expected shouldLoadTrack to return true after startLoad() is called' ).to.be.true; expect(audioTrackLoadingCallback).to.have.been.calledOnce; }); it('should not attempt to load audio tracks without a url', function () { const shouldLoadTrack = sinon.spy( audioTrackController, 'shouldLoadTrack' ); const audioTrackLoadingCallback = sinon.spy(); const trackWithOutUrl = tracks[0]; hls.on(Hls.Events.AUDIO_TRACK_LOADING, audioTrackLoadingCallback); hls.levelController = { levels: [ { urlId: 0, audioGroupIds: ['1'], }, ], }; audioTrackController.tracks = tracks; audioTrackController.onLevelLoading(Events.LEVEL_LOADING, { level: 0, }); audioTrackController.startLoad(0); expect(shouldLoadTrack).to.have.been.calledTwice; expect(shouldLoadTrack).to.have.been.calledWith(trackWithOutUrl); expect(shouldLoadTrack.firstCall.returnValue).to.be.false; expect(shouldLoadTrack.secondCall.returnValue).to.be.false; expect(audioTrackLoadingCallback).to.not.have.been.called; }); }); describe('onError', function () { it('should clear interval (only) on fatal network errors', function () { audioTrackController.timer = 1000; audioTrackController.onError(Events.ERROR, { type: Hls.ErrorTypes.MEDIA_ERROR, }); expect(audioTrackController.timer).to.equal(1000); audioTrackController.onError(Events.ERROR, { type: Hls.ErrorTypes.MEDIA_ERROR, fatal: true, }); expect(audioTrackController.timer).to.equal(1000); audioTrackController.onError(Events.ERROR, { type: Hls.ErrorTypes.NETWORK_ERROR, fatal: false, }); expect(audioTrackController.timer).to.equal(1000); audioTrackController.onError(Events.ERROR, { type: Hls.ErrorTypes.NETWORK_ERROR, fatal: true, }); expect(audioTrackController.timer).to.equal(-1); }); it('should retry track loading if track has not changed', function () { const retryLoadingOrFail = sinon.spy( audioTrackController, 'retryLoadingOrFail' ); const currentTrackId = 4; const currentGroupId = 'aac'; audioTrackController.trackId = currentTrackId; audioTrackController.groupId = currentGroupId; audioTrackController.tracks = tracks; audioTrackController.onError(Events.ERROR, { type: Hls.ErrorTypes.NETWORK_ERROR, details: Hls.ErrorDetails.AUDIO_TRACK_LOAD_ERROR, fatal: false, context: { type: PlaylistContextType.AUDIO_TRACK, id: currentTrackId, groupId: currentGroupId, }, }); expect( audioTrackController.audioTrack, 'track index/id is not changed as there is no redundant track to choose from' ).to.equal(4); expect(retryLoadingOrFail).to.have.been.calledOnce; }); }); });
the_stack
import {assert} from 'chai'; import * as CHANNEL from 'vega-lite/build/src/channel'; import * as MARK from 'vega-lite/build/src/mark'; import {TitleParams} from 'vega-lite/build/src/title'; import * as TYPE from 'vega-lite/build/src/type'; import {DEFAULT_QUERY_CONFIG} from '../src/config'; import {SpecQueryModel, SpecQueryModelGroup} from '../src/model'; import {ENCODING_NESTED_PROPS, ENCODING_TOPLEVEL_PROPS, Property, toKey} from '../src/property'; import {AutoCountQuery, FieldQuery} from '../src/query/encoding'; import {SpecQuery} from '../src/query/spec'; import {FieldSchema, Schema} from '../src/schema'; import {duplicate, extend} from '../src/util'; import {getDefaultEnumValues, isWildcard, SHORT_WILDCARD} from '../src/wildcard'; import {schema} from './fixture'; const DEFAULT_SPEC_CONFIG = DEFAULT_QUERY_CONFIG.defaultSpecConfig; describe('SpecQueryModel', () => { function buildSpecQueryModel(specQ: SpecQuery) { return SpecQueryModel.build(specQ, schema, DEFAULT_QUERY_CONFIG); } describe('build', () => { // Mark it('should have mark wildcardIndex if mark is a ShortWildcard.', () => { const specQ: SpecQuery = { mark: SHORT_WILDCARD, encodings: [], }; const wildcardIndex = SpecQueryModel.build(specQ, schema, DEFAULT_QUERY_CONFIG).wildcardIndex; assert.deepEqual(wildcardIndex.mark, { name: 'm', enum: DEFAULT_QUERY_CONFIG.enum.mark, }); }); it('should have mark wildcardIndex if mark is an Wildcard.', () => { const specQ: SpecQuery = { mark: { enum: [MARK.BAR], }, encodings: [], }; const wildcardIndex = SpecQueryModel.build(specQ, schema, DEFAULT_QUERY_CONFIG).wildcardIndex; assert.deepEqual(wildcardIndex.mark, { name: 'm', enum: [MARK.BAR], }); }); it('should have no mark wildcardIndex if mark is specific.', () => { const specQ: SpecQuery = { mark: MARK.BAR, encodings: [], }; const wildcardIndex = SpecQueryModel.build(specQ, schema, DEFAULT_QUERY_CONFIG).wildcardIndex; assert.isNotOk(wildcardIndex.mark); }); // TODO: Transform // Encoding describe('type', () => { it('should automatically add type as wildcard and index it', () => { const specQ: SpecQuery = { mark: MARK.POINT, encodings: [{channel: CHANNEL.X, field: 'A'}], }; const specM = SpecQueryModel.build(specQ, schema, DEFAULT_QUERY_CONFIG); // check if type is wildcard assert.isTrue(isWildcard((specM.getEncodingQueryByIndex(0) as FieldQuery).type)); // check if enumeration specifier index has an index for type assert.isOk(specM.wildcardIndex.encodings[0].get('type')); }); }); const templateSpecQ: SpecQuery = { mark: MARK.POINT, encodings: [{channel: CHANNEL.X, field: 'a', type: TYPE.QUANTITATIVE}], }; ENCODING_TOPLEVEL_PROPS.forEach((prop) => { it(`should have ${prop} wildcardIndex if it is a ShortWildcard.`, () => { const specQ = duplicate(templateSpecQ); // set to a short wildcard specQ.encodings[0][prop] = SHORT_WILDCARD; const wildcardIndex = SpecQueryModel.build(specQ, schema, DEFAULT_QUERY_CONFIG).wildcardIndex; assert.isOk(wildcardIndex.encodingIndicesByProperty.get(prop)); assert.isOk(wildcardIndex.encodings[0].get(prop)); }); it(`should have ${prop} wildcardIndex if it is an Wildcard.`, () => { const specQ = duplicate(templateSpecQ); // set to a full wildcard const enumValues = prop === Property.FIELD ? ['A', 'B'] : getDefaultEnumValues(prop, schema, DEFAULT_QUERY_CONFIG); specQ.encodings[0][prop] = { enum: enumValues, }; const wildcardIndex = SpecQueryModel.build(specQ, schema, DEFAULT_QUERY_CONFIG).wildcardIndex; assert.isOk(wildcardIndex.encodingIndicesByProperty.get(prop)); assert.isOk(wildcardIndex.encodings[0].get(prop)); }); it(`should not have ${prop} wildcardIndex if it is specific.`, () => { const specQ = duplicate(templateSpecQ); // do not set to wildcard = make it specific const wildcardIndex = SpecQueryModel.build(specQ, schema, DEFAULT_QUERY_CONFIG).wildcardIndex; assert.isNotOk(wildcardIndex.encodingIndicesByProperty.get(prop)); assert.isNotOk(wildcardIndex.encodings[0]); }); }); ENCODING_NESTED_PROPS.forEach((nestedProp) => { const propKey = toKey(nestedProp); const parent = nestedProp.parent; const child = nestedProp.child; it(`should have ${propKey} wildcardIndex if it is a ShortWildcard.`, () => { const specQ = duplicate(templateSpecQ); // set to a short wildcard specQ.encodings[0][parent] = {}; specQ.encodings[0][parent][child] = SHORT_WILDCARD; const wildcardIndex = SpecQueryModel.build(specQ, schema, DEFAULT_QUERY_CONFIG).wildcardIndex; assert.isOk(wildcardIndex.encodingIndicesByProperty.get(nestedProp)); assert.isOk(wildcardIndex.encodings[0].get(nestedProp)); }); it(`should have ${propKey} wildcardIndex if it is an Wildcard.`, () => { const specQ = duplicate(templateSpecQ); specQ.encodings[0][parent] = {}; specQ.encodings[0][parent][child] = { enum: getDefaultEnumValues(nestedProp, schema, DEFAULT_QUERY_CONFIG), }; const wildcardIndex = SpecQueryModel.build(specQ, schema, DEFAULT_QUERY_CONFIG).wildcardIndex; assert.isOk(wildcardIndex.encodingIndicesByProperty.get(nestedProp)); assert.isOk(wildcardIndex.encodings[0].get(nestedProp)); }); it(`should not have ${propKey} wildcardIndex if it is specific.`, () => { const specQ = duplicate(templateSpecQ); const wildcardIndex = SpecQueryModel.build(specQ, schema, DEFAULT_QUERY_CONFIG).wildcardIndex; assert.isNotOk(wildcardIndex.encodingIndicesByProperty.get(nestedProp)); assert.isNotOk(wildcardIndex.encodings[0]); }); }); describe('autoCount', () => { const specQ: SpecQuery = { mark: MARK.POINT, encodings: [{channel: CHANNEL.X, field: 'a', type: TYPE.ORDINAL}], }; const model = SpecQueryModel.build(specQ, schema, extend({}, DEFAULT_QUERY_CONFIG, {autoAddCount: true})); it('should add new encoding if autoCount is enabled', () => { assert.equal(model.specQuery.encodings.length, 2); assert.isTrue(isWildcard((model.specQuery.encodings[1] as AutoCountQuery).autoCount)); }); it('should add new channel and autoCount to the wildcard', () => { assert.equal(model.wildcardIndex.encodingIndicesByProperty.get('autoCount')[0], 1); assert.equal(model.wildcardIndex.encodingIndicesByProperty.get('channel')[0], 1); }); }); }); describe('channelUsed', () => { it('should return true if channel is used for general fieldDef', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, encodings: [{channel: CHANNEL.X, field: 'A', type: TYPE.QUANTITATIVE, aggregate: 'max'}], }); assert.isTrue(specM.channelUsed(CHANNEL.X)); }); it('should return false if channel is used for general fieldDef', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, encodings: [{channel: CHANNEL.X, field: 'A', type: TYPE.QUANTITATIVE, aggregate: 'max'}], }); assert.isFalse(specM.channelUsed(CHANNEL.Y)); }); it('should return false if channel is used for disabled autoCount', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, encodings: [{channel: CHANNEL.X, autoCount: false}], }); assert.isFalse(specM.channelUsed(CHANNEL.X)); }); }); describe('isAggregate', () => { it('should return false if the query is not aggregated', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, encodings: [{channel: CHANNEL.X, field: 'A', type: TYPE.QUANTITATIVE}], }); assert.isFalse(specM.isAggregate()); }); it('should return true if the query is aggregated', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, encodings: [{channel: CHANNEL.X, field: 'A', type: TYPE.QUANTITATIVE, aggregate: 'max'}], }); assert.isTrue(specM.isAggregate()); }); it('should return true if the query has autoCount = true', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, encodings: [{channel: CHANNEL.X, autoCount: true}], }); assert.isTrue(specM.isAggregate()); }); }); describe('getEncodings()', () => { it('should return correct encodings', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, encodings: [ {channel: CHANNEL.Y, value: 5}, {channel: CHANNEL.COLOR, field: 'a', type: 'quantitative'}, {channel: CHANNEL.X, autoCount: false}, ], }); assert.deepEqual(specM.getEncodings(), [ {channel: CHANNEL.Y, value: 5}, {channel: CHANNEL.COLOR, field: 'a', type: 'quantitative'}, ]); }); }); describe('toSpec', () => { it('should not return a Vega-Lite spec if an encoding property is wildcard', () => { const specM = buildSpecQueryModel({ data: {values: [{Q: 1}]}, transform: [{filter: 'datum.Q===1'}], mark: MARK.BAR, encodings: [ { channel: CHANNEL.X, field: '?', type: TYPE.QUANTITATIVE, }, ], }); const spec = specM.toSpec(); assert.isNull(spec); }); it('should return a Vega-Lite spec if the query is completed', () => { const specM = buildSpecQueryModel({ data: {values: [{Q: 1}]}, transform: [{filter: 'datum.Q===1'}], mark: MARK.BAR, encodings: [ { channel: CHANNEL.X, field: 'Q', type: TYPE.QUANTITATIVE, axis: {orient: 'top', tickCount: 5, title: 'test x channel'}, }, { channel: CHANNEL.COLOR, field: 'Q2', type: TYPE.QUANTITATIVE, legend: {orient: 'right', labelAlign: 'left', symbolSize: 12, title: 'test title'}, }, ], }); const spec = specM.toSpec(); assert.deepEqual(spec, { data: {values: [{Q: 1}]}, transform: [{filter: 'datum.Q===1'}], mark: MARK.BAR, encoding: { x: { field: 'Q', type: TYPE.QUANTITATIVE, axis: {orient: 'top', tickCount: 5, title: 'test x channel'}, }, color: { field: 'Q2', type: TYPE.QUANTITATIVE, legend: {orient: 'right', labelAlign: 'left', symbolSize: 12, title: 'test title'}, }, }, config: DEFAULT_SPEC_CONFIG, }); }); it('should return a Vega-Lite spec that does not output inapplicable legend', () => { const specM = buildSpecQueryModel({ data: {values: [{Q: 1}]}, transform: [{filter: 'datum.Q===1'}], mark: MARK.BAR, encodings: [ { channel: CHANNEL.X, field: 'Q', type: TYPE.QUANTITATIVE, axis: {orient: 'top', tickCount: 5, title: 'test x channel'}, legend: {orient: 'right', labelAlign: 'left', symbolSize: 12, title: 'test title'}, }, ], }); const spec = specM.toSpec(); assert.deepEqual(spec, { data: {values: [{Q: 1}]}, transform: [{filter: 'datum.Q===1'}], mark: MARK.BAR, encoding: { x: { field: 'Q', type: TYPE.QUANTITATIVE, axis: {orient: 'top', tickCount: 5, title: 'test x channel'}, }, }, config: DEFAULT_SPEC_CONFIG, }); }); it('should return a Vega-Lite spec that does not output inapplicable axis', () => { const specQ: SpecQuery = { data: {values: [{Q: 1}]}, transform: [{filter: 'datum.Q===1'}], mark: MARK.BAR, encodings: [ { channel: CHANNEL.COLOR, field: 'Q2', type: TYPE.QUANTITATIVE, axis: {orient: 'top', tickCount: 5, title: 'test x channel'}, legend: {orient: 'right', labelAlign: 'left', symbolSize: 12, title: 'test title'}, }, ], }; const specM = buildSpecQueryModel(specQ); const spec = specM.toSpec(); assert.deepEqual(spec, { data: {values: [{Q: 1}]}, transform: [{filter: 'datum.Q===1'}], mark: MARK.BAR, encoding: { color: { field: 'Q2', type: TYPE.QUANTITATIVE, legend: {orient: 'right', labelAlign: 'left', symbolSize: 12, title: 'test title'}, }, }, config: DEFAULT_SPEC_CONFIG, }); }); it('should return a spec with no bin if the bin=false.', () => { const specM = buildSpecQueryModel({ data: {values: [{Q: 1}]}, mark: MARK.BAR, encodings: [{channel: CHANNEL.X, bin: false, field: 'Q', type: TYPE.QUANTITATIVE}], }); const spec = specM.toSpec(); assert.deepEqual(spec, { data: {values: [{Q: 1}]}, mark: MARK.BAR, encoding: { x: {field: 'Q', type: TYPE.QUANTITATIVE}, }, config: DEFAULT_SPEC_CONFIG, }); }); it( 'should return a spec with the domain specified in FieldSchema if the encoding query ' + 'already has scale but does not have domain', () => { const specM = SpecQueryModel.build( { data: { values: [ {A: 'L', B: 4}, {A: 'S', B: 2}, {A: 'M', B: 42}, ], }, mark: MARK.BAR, encodings: [ {channel: CHANNEL.X, field: 'A', type: TYPE.ORDINAL, scale: {}}, {channel: CHANNEL.Y, field: 'B', type: TYPE.QUANTITATIVE}, ], }, new Schema({ fields: [ { name: 'A', vlType: 'ordinal', type: 'string' as any, ordinalDomain: ['S', 'M', 'L'], stats: { distinct: 3, }, }, { name: 'B', vlType: 'quantitative', type: 'number' as any, stats: { distinct: 3, }, }, ] as FieldSchema[], }), DEFAULT_QUERY_CONFIG ); const spec = specM.toSpec(); assert.deepEqual(spec, { data: { values: [ {A: 'L', B: 4}, {A: 'S', B: 2}, {A: 'M', B: 42}, ], }, mark: MARK.BAR, encoding: { x: {field: 'A', type: TYPE.ORDINAL, scale: {domain: ['S', 'M', 'L']}}, y: {field: 'B', type: TYPE.QUANTITATIVE}, }, config: DEFAULT_SPEC_CONFIG, }); } ); it( 'should return a spec with the domain specified in FieldSchema if the encoding query ' + 'already has scale set to true', () => { const specM = SpecQueryModel.build( { data: { values: [ {A: 'L', B: 4}, {A: 'S', B: 2}, {A: 'M', B: 42}, ], }, mark: MARK.BAR, encodings: [ {channel: CHANNEL.X, field: 'A', type: TYPE.ORDINAL, scale: true}, {channel: CHANNEL.Y, field: 'B', type: TYPE.QUANTITATIVE}, ], }, new Schema({ fields: [ { name: 'A', vlType: 'ordinal', type: 'string' as any, ordinalDomain: ['S', 'M', 'L'], stats: { distinct: 3, }, }, { name: 'B', vlType: 'quantitative', type: 'number' as any, stats: { distinct: 3, }, }, ] as FieldSchema[], }), DEFAULT_QUERY_CONFIG ); const spec = specM.toSpec(); assert.deepEqual(spec, { data: { values: [ {A: 'L', B: 4}, {A: 'S', B: 2}, {A: 'M', B: 42}, ], }, mark: MARK.BAR, encoding: { x: {field: 'A', type: TYPE.ORDINAL, scale: {domain: ['S', 'M', 'L']}}, y: {field: 'B', type: TYPE.QUANTITATIVE}, }, config: DEFAULT_SPEC_CONFIG, }); } ); it('should return a spec with the domain specified in FieldSchema if the encoding query scale is undefined', () => { const specM = SpecQueryModel.build( { data: { values: [ {A: 'L', B: 4}, {A: 'S', B: 2}, {A: 'M', B: 42}, ], }, mark: MARK.BAR, encodings: [ {channel: CHANNEL.X, field: 'A', type: TYPE.ORDINAL}, {channel: CHANNEL.Y, field: 'B', type: TYPE.QUANTITATIVE}, ], }, new Schema({ fields: [ { name: 'A', vlType: 'ordinal', type: 'string' as any, ordinalDomain: ['S', 'M', 'L'], stats: { distinct: 3, }, }, { name: 'B', vlType: 'quantitative', type: 'number' as any, stats: { distinct: 3, }, }, ] as FieldSchema[], }), DEFAULT_QUERY_CONFIG ); const spec = specM.toSpec(); assert.deepEqual(spec, { data: { values: [ {A: 'L', B: 4}, {A: 'S', B: 2}, {A: 'M', B: 42}, ], }, mark: MARK.BAR, encoding: { x: {field: 'A', type: TYPE.ORDINAL, scale: {domain: ['S', 'M', 'L']}}, y: {field: 'B', type: TYPE.QUANTITATIVE}, }, config: DEFAULT_SPEC_CONFIG, }); }); it('should return a spec with the domain that is already set in an Encoding Query', () => { const specM = SpecQueryModel.build( { data: { values: [ {A: 'L', B: 4}, {A: 'S', B: 2}, {A: 'M', B: 42}, ], }, mark: MARK.BAR, encodings: [ {channel: CHANNEL.X, field: 'A', type: TYPE.ORDINAL, scale: {domain: ['L', 'M', 'S']}}, {channel: CHANNEL.Y, field: 'B', type: TYPE.QUANTITATIVE}, ], }, new Schema({ fields: [ { name: 'A', vlType: 'ordinal', type: 'string' as any, ordinalDomain: ['S', 'M', 'L'], stats: { distinct: 3, }, }, { name: 'B', vlType: 'quantitative', type: 'number' as any, stats: { distinct: 3, }, }, ] as FieldSchema[], }), DEFAULT_QUERY_CONFIG ); const spec = specM.toSpec(); assert.deepEqual(spec, { data: { values: [ {A: 'L', B: 4}, {A: 'S', B: 2}, {A: 'M', B: 42}, ], }, mark: MARK.BAR, encoding: { x: {field: 'A', type: TYPE.ORDINAL, scale: {domain: ['L', 'M', 'S']}}, y: {field: 'B', type: TYPE.QUANTITATIVE}, }, config: DEFAULT_SPEC_CONFIG, }); }); it('should return a spec with bin as object if the bin has no parameter.', () => { const specM = buildSpecQueryModel({ data: {values: [{Q: 1}]}, mark: MARK.BAR, encodings: [{channel: CHANNEL.X, bin: {maxbins: 50}, field: 'Q', type: TYPE.QUANTITATIVE}], }); const spec = specM.toSpec(); assert.deepEqual(spec, { data: {values: [{Q: 1}]}, mark: MARK.BAR, encoding: { x: {bin: {maxbins: 50}, field: 'Q', type: TYPE.QUANTITATIVE}, }, config: DEFAULT_SPEC_CONFIG, }); }); it('should return a correct Vega-Lite spec if the query has sort: SortOrder', () => { const specM = buildSpecQueryModel({ data: {values: [{Q: 1, O: 1}]}, transform: [{filter: 'datum.Q===1'}], mark: MARK.BAR, encodings: [ {channel: CHANNEL.X, field: 'Q', aggregate: 'mean', type: TYPE.QUANTITATIVE}, {channel: CHANNEL.Y, field: 'O', sort: {field: 'Q', op: 'mean', order: 'ascending'}, type: TYPE.ORDINAL}, ], }); const spec = specM.toSpec(); assert.deepEqual(spec, { data: {values: [{Q: 1, O: 1}]}, transform: [{filter: 'datum.Q===1'}], mark: MARK.BAR, encoding: { x: {field: 'Q', aggregate: 'mean', type: TYPE.QUANTITATIVE}, y: {field: 'O', sort: {field: 'Q', op: 'mean', order: 'ascending'}, type: TYPE.ORDINAL}, }, config: DEFAULT_SPEC_CONFIG, }); }); it('should return a correct Vega-Lite spec if the query has autoCount=true', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, encodings: [ {channel: CHANNEL.X, field: 'O', type: TYPE.ORDINAL}, {channel: CHANNEL.Y, autoCount: true, type: TYPE.QUANTITATIVE}, ], }); const spec = specM.toSpec(); assert.deepEqual(spec, { mark: MARK.BAR, encoding: { x: {field: 'O', type: TYPE.ORDINAL}, y: {aggregate: 'count', field: '*', type: TYPE.QUANTITATIVE}, }, config: DEFAULT_SPEC_CONFIG, }); }); it('should return a correct Vega-Lite spec if the query has autoCount=false', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, encodings: [ {channel: CHANNEL.X, field: 'O', type: TYPE.ORDINAL}, {channel: CHANNEL.Y, autoCount: false}, ], }); const spec = specM.toSpec(); assert.deepEqual(spec, { mark: MARK.BAR, encoding: { x: {field: 'O', type: TYPE.ORDINAL}, }, config: DEFAULT_SPEC_CONFIG, }); }); it('should return a correct Vega-Lite spec if the query has autoCount=false even if channel is unspecified', () => { // Basically, we no longer enumerate ambiguous channel autoCount is false. const specM = buildSpecQueryModel({ mark: MARK.BAR, encodings: [ {channel: CHANNEL.X, field: 'O', type: TYPE.ORDINAL}, {channel: SHORT_WILDCARD, autoCount: false}, ], }); const spec = specM.toSpec(); assert.deepEqual(spec, { mark: MARK.BAR, encoding: { x: {field: 'O', type: TYPE.ORDINAL}, }, config: DEFAULT_SPEC_CONFIG, }); }); it('should return null if the query is incompleted', () => { const specM = buildSpecQueryModel({ mark: {enum: [MARK.BAR, MARK.POINT]}, encodings: [{channel: CHANNEL.X, field: 'A', type: TYPE.QUANTITATIVE}], config: DEFAULT_SPEC_CONFIG, }); assert.isNull(specM.toSpec()); }); it('should not output spec with inapplicable scale, sort, axis / legend', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, encodings: [{channel: CHANNEL.X, bin: {maxbins: '?'}, field: 'A', type: TYPE.QUANTITATIVE}], }); assert.isNull(specM.toSpec()); }); it('should return a spec with width and height specified', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, width: 100, height: 120, encodings: [{channel: CHANNEL.X, field: 'O', type: TYPE.ORDINAL}], }); assert.equal(specM.toSpec().width, 100); assert.equal(specM.toSpec().height, 120); }); it('should return a spec with background color as specified', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, background: 'black', encodings: [{channel: CHANNEL.X, field: 'O', type: TYPE.ORDINAL}], }); assert.equal(specM.toSpec().background, 'black'); }); it('should return a spec with padding as specified', () => { const specM = buildSpecQueryModel({ mark: MARK.BAR, padding: { left: 1, top: 2, right: 3, bottom: 4, }, encodings: [{channel: CHANNEL.X, field: 'O', type: TYPE.ORDINAL}], }); assert.deepEqual(specM.toSpec().padding, {left: 1, top: 2, right: 3, bottom: 4}); }); it('should return a spec with a title string specified', () => { const specM = buildSpecQueryModel({ title: 'Big Title', mark: MARK.BAR, encodings: [{channel: CHANNEL.X, field: 'O', type: TYPE.ORDINAL}], }); assert.equal(specM.toSpec().title, 'Big Title'); }); it('should return a spec with a title params specified', () => { const specM = buildSpecQueryModel({ title: { text: 'A Simple Bar Chart', anchor: 'start', }, mark: MARK.BAR, encodings: [{channel: CHANNEL.X, field: 'O', type: TYPE.ORDINAL}], }); const title = specM.toSpec().title as TitleParams<any>; assert.equal(title.text, 'A Simple Bar Chart'); assert.equal(title.anchor, 'start'); }); }); }); describe('SpecQueryModelGroup', () => { describe('constructor', () => { const group: SpecQueryModelGroup = { name: '', path: '', items: [], }; it('should have default values', () => { assert.equal(group.name, ''); assert.equal(group.path, ''); assert.isArray(group.items); assert.deepEqual(group.items, []); assert.equal(group.groupBy, undefined); assert.equal(group.orderGroupBy, undefined); }); }); });
the_stack
import { API, DynamicPlatformPlugin, Logger, PlatformAccessory, PlatformConfig, Service, Characteristic } from "homebridge"; import { PLATFORM_NAME, PLUGIN_NAME } from "./settings"; import { DeviceInfo, Device, EMPTY_DEVICEINFO } from "./yeedevice"; import { YeeAccessory} from "./yeeaccessory"; import { Discovery } from "./discovery"; import { TRACKED_ATTRIBUTES, OverrideLightConfiguration } from "./yeeaccessory"; interface ManualOverride { id: string; address: string; model: string; name?: string; log?: boolean; color: boolean; backgroundLight: boolean; nightLight: boolean; separateAmbient?: boolean; support: string; } /** * HomebridgePlatform * This class is the main constructor for your plugin, this is where you should * parse the user config and discover/register accessories with Homebridge. */ export class YeelighterPlatform implements DynamicPlatformPlugin { public readonly Service: typeof Service = this.api.hap.Service; public readonly Characteristic: typeof Characteristic = this.api.hap.Characteristic; // this is used to track restored cached accessories public readonly accessories: PlatformAccessory[] = []; private agent: Discovery; constructor( public readonly log: Logger, public readonly config: PlatformConfig, public readonly api: API, ) { this.log.debug("Finished initializing platform:", this.config.name); this.agent = new Discovery(); this.agent.on("started", () => { this.log.debug("** Discovery Started **"); }); this.agent.on("didDiscoverDevice", this.onDeviceDiscovery); // When this event is fired it means Homebridge has restored all cached accessories from disk. // Dynamic Platform plugins should only register new accessories after this event was fired, // in order to ensure they weren't added to homebridge already. This event can also be used // to start discovery of new accessories. this.api.on("didFinishLaunching", () => { this.log.debug("Executed didFinishLaunching callback"); this.agent.listen(); this.addHardCodedAccessories(); }); } /** * This function is invoked when homebridge restores cached accessories from disk at startup. * It should be used to setup event handlers for characteristics and update respective values. */ configureAccessory(accessory: PlatformAccessory) { if (this.accessories.find(a => a.UUID === accessory.UUID)) { this.log.warn(`Ingnoring duplicate accessory from cache: ${accessory.displayName} (${accessory.context?.device?.model || "unknown"})`); return; } this.log.info(`Loading accessory from cache: ${accessory.displayName} (${accessory.context?.device?.model || "unknown"})`); // add the restored accessory to the accessories cache so we can track if it has already been registered this.accessories.push(accessory); } // called when a Yeelight has responded to the discovery query private onDeviceDiscovery = (detectedInfo: DeviceInfo) => { try { const trackedAttributes = TRACKED_ATTRIBUTES; // .filter(attribute => supportedAttributes.includes(attribute)); const override: OverrideLightConfiguration[] = this.config.override as OverrideLightConfiguration[] || []; const overrideConfig: OverrideLightConfiguration | undefined = override.find( item => item.id === detectedInfo.id, ); const separateAmbient = ((this.config?.split && overrideConfig?.separateAmbient !== false) || overrideConfig?.separateAmbient === true) && (detectedInfo.support.includes("bg_set_power") || !!overrideConfig?.backgroundLight); const newDeviceInfo: DeviceInfo = { ...detectedInfo, trackedAttributes, }; // generate a unique id for the accessory this should be generated from // something globally unique, but constant, for example, the device serial // number or MAC address const uuid = this.api.hap.uuid.generate(newDeviceInfo.id); // if the device has a secondary (ambient) light and is configured to have // this shown as a separate top-level light, generate a separate UUID for it const ambientUuid = this.api.hap.uuid.generate(`${newDeviceInfo.id}#ambient`); if (overrideConfig) { this.log.info(`Override config for ${detectedInfo.id}: ${JSON.stringify(overrideConfig)}`); if (overrideConfig.ignored) { this.log.info(`Ignoring ${detectedInfo.id} as configured.`); // see if an accessory with the same uuid has already been registered and restored from // the cached devices we stored in the `configureAccessory` method above const existingAccessory = this.accessories.find(accessory => accessory.UUID === uuid); const purgeList: PlatformAccessory[] = []; if (existingAccessory) { this.log.info("Removing ignored accessory from cache:", existingAccessory.displayName); purgeList.push(existingAccessory); } const existingAmbientAccessory = this.accessories.find(accessory => accessory.UUID === ambientUuid); if (existingAmbientAccessory) { purgeList.push(existingAmbientAccessory); this.log.info("Removing ignored ambient accessory from cache:", existingAmbientAccessory.displayName); } if (purgeList.length > 0) { try { purgeList.forEach(item => { const index = this.accessories.indexOf(item); if (index >= 0) { this.accessories.splice(index, 1); } }) this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, purgeList); } catch (error) { this.log.warn("Failed to unregister", purgeList, error); } } return; } } const device = new Device(newDeviceInfo); // see if an accessory with the same uuid has already been registered and restored from // the cached devices we stored in the `configureAccessory` method above const existingAccessory = this.accessories.find(accessory => accessory.UUID === uuid); let ambientAccessory = this.accessories.find(accessory => accessory.UUID === ambientUuid); if (ambientAccessory && !separateAmbient) { try { this.log.info(`Separate Ambient Accessory not wanted anymore. Unregistering`, ambientAccessory.UUID); const index = this.accessories.indexOf(ambientAccessory); if (index >= 0) { this.accessories.splice(index, 1); } this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [ambientAccessory]); // TODO: remove from this.accessories } catch (error) { this.log.warn("failed to unregister", ambientAccessory.UUID, error); } ambientAccessory = undefined; } if (existingAccessory) { // the accessory already exists if (device) { this.log.info(`New (cached) ${newDeviceInfo.model} [${newDeviceInfo.id}] found at ${newDeviceInfo.location}`); // update the accessory.context existingAccessory.context.device = newDeviceInfo; const updateAccessories = [existingAccessory]; if (!ambientAccessory && separateAmbient) { ambientAccessory = new this.api.platformAccessory(newDeviceInfo.id, ambientUuid); ambientAccessory.context.device = newDeviceInfo; this.log.info(`Separate Ambient Accessory created with UUID ${ambientUuid}`); // link the accessory to your platform this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [ambientAccessory]); updateAccessories.push(ambientAccessory); } YeeAccessory.instance(device, this, existingAccessory, ambientAccessory); // update accessory cache with any changes to the accessory details and information this.api.updatePlatformAccessories(updateAccessories); } else { // it is possible to remove platform accessories at any time using `api.unregisterPlatformAccessories`, eg.: // remove platform accessories when no longer present try { this.log.info("Removing existing accessory from cache:", existingAccessory.displayName); this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [existingAccessory]); const index = this.accessories.indexOf(existingAccessory); if (index >= 0) { this.accessories.splice(index, 1); } } catch (error) { this.log.warn("Failed to remove accessory", existingAccessory, error); } } } else { const addedAccessories: PlatformAccessory[] = []; // the accessory does not yet exist, so we need to create it this.log.info(`New ${newDeviceInfo.model} [${newDeviceInfo.id}] found at ${newDeviceInfo.location}`); const accessory = new this.api.platformAccessory(newDeviceInfo.id, uuid); // store a copy of the device object in the `accessory.context` // the `context` property can be used to store any data about the accessory you may need accessory.context.device = newDeviceInfo; this.configureAccessory(accessory); addedAccessories.push(accessory); this.log.info(`Accessory created with UUID ${uuid}`); if (separateAmbient && !ambientAccessory) { ambientAccessory = new this.api.platformAccessory(newDeviceInfo.id, ambientUuid); ambientAccessory.context.device = newDeviceInfo; this.configureAccessory(ambientAccessory); addedAccessories.push(ambientAccessory); this.log.info(`Separate Ambient Accessory created with UUID ${ambientUuid}`); } // create the accessory handler for the newly create accessory YeeAccessory.instance(device, this, accessory, ambientAccessory); // link the accessory to your platform this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, addedAccessories); } } catch (error) { this.log.error("Device discovery handling failed", error); } }; private addHardCodedAccessories() { const manualAccessories: ManualOverride[] = this.config?.manual as ManualOverride[] || []; this.log.info(`adding ${manualAccessories.length} manual accessories`); for (const manualAccessory of manualAccessories) { const deviceInfo: DeviceInfo = { ...EMPTY_DEVICEINFO }; deviceInfo.location = `yeelight://${manualAccessory.address}`; deviceInfo.id = manualAccessory.id; deviceInfo.model = manualAccessory.model; deviceInfo.support = manualAccessory.support; this.onDeviceDiscovery(deviceInfo); } } }
the_stack
import { existsSync, mkdirSync, writeFile } from 'fs' import { basename, dirname, resolve } from 'path' import { createFilter, CreateFilter } from 'rollup-pluginutils' import type { Plugin } from 'rollup' export interface CSSPluginOptions { exclude?: Parameters<CreateFilter>[1] failOnError?: boolean include?: Parameters<CreateFilter>[0] includePaths?: string[] insert?: boolean output?: string | false | ((css: string, styles: Styles) => void) prefix?: string processor?: ( css: string, map: string, styles: Styles ) => CSS | Promise<CSS> | PostCSSProcessor sass?: SassRenderer sourceMap?: boolean verbose?: boolean watch?: string | string[] } type ImporterReturnType = { file: string } | { contents: string } | Error | null type ImporterDoneCallback = (data: ImporterReturnType) => void type CSS = string | { css: string; map: string } interface MappedCSS { css: string map: string } interface Styles { [id: string]: string } interface PostCSSProcessor { process: (css: string, options?: any) => MappedCSS } interface SassRenderer { renderSync: (options: SassOptions) => SassResult } interface SassOptions { data: string } interface SassResult { css: Buffer map?: Buffer } export default function scss(options: CSSPluginOptions = {}): Plugin { const filter = createFilter( options.include || ['/**/*.css', '/**/*.scss', '/**/*.sass'], options.exclude ) let dest = typeof options.output === 'string' ? options.output : null const insertStyleFnName = '___$insertStylesToHeader' const styles: Styles = {} const prefix = options.prefix ? options.prefix + '\n' : '' let includePaths = options.includePaths || ['node_modules/'] includePaths.push(process.cwd()) const compileToCSS = async function (scss: string) { // Compile SASS to CSS if (scss.length) { includePaths = includePaths.filter((v, i, a) => a.indexOf(v) === i) try { const sass = options.sass || loadSassLibrary() const render = sass.renderSync( Object.assign( { data: prefix + scss, outFile: dest, includePaths, importer: ( url: string, prev: string, done: ImporterDoneCallback ): ImporterReturnType | void => { /* If a path begins with `.`, then it's a local import and this * importer cannot handle it. This check covers both `.` and * `..`. * * Additionally, if an import path begins with `url` or `http`, * then it's a remote import, this importer also cannot handle * that. */ if ( url.startsWith('.') || url.startsWith('url') || url.startsWith('http') ) { /* The importer returns `null` to defer processing the import * back to the sass compiler. */ return null } /* If the requested path begins with a `~`, we remove it. This * character is used by webpack-contrib's sass-loader to * indicate the import is from the node_modules folder. Since * this is so standard in the JS world, the importer supports * it, by removing it and ignoring it. */ const cleanUrl = url.startsWith('~') ? url.replace('~', '') : url /* Now, the importer uses `require.resolve()` to attempt * to resolve the path to the requested file. In the case * of a standard node_modules project, this will use Node's * `require.resolve()`. In the case of a Plug 'n Play project, * this will use the `require.resolve()` provided by the * package manager. * * This statement is surrounded by a try/catch block because * if Node or the package manager cannot resolve the requested * file, they will throw an error, so the importer needs to * defer to sass, by returning `null`. * * The paths property tells `require.resolve()` where to begin * resolution (i.e. who is requesting the file). */ try { const resolved = require.resolve(cleanUrl, { paths: [prefix + scss] }) /* Since `require.resolve()` will throw an error if a file * doesn't exist. It's safe to assume the file exists and * pass it off to the sass compiler. */ return { file: resolved } } catch (e: any) { /* Just because `require.resolve()` couldn't find the file * doesn't mean it doesn't exist. It may still be a local * import that just doesn't list a relative path, so defer * processing back to sass by returning `null` */ return null } } }, options ) ) const css = render.css.toString() const map = render.map ? render.map.toString() : '' // Possibly process CSS (e.g. by PostCSS) if (typeof options.processor === 'function') { const result = await options.processor(css, map, styles) // TODO: figure out how to check for // @ts-ignore const postcss: PostCSSProcessor = result // PostCSS support if (typeof postcss.process === 'function') { return Promise.resolve( postcss.process(css, { from: undefined, to: dest, map: map ? { prev: map, inline: false } : null }) ) } // @ts-ignore const output: string | MappedCSS = result return stringToCSS(output) } return { css, map } } catch (e) { if (options.failOnError) { throw e } console.log() console.log(red('Error:\n\t' + e.message)) if (e.message.includes('Invalid CSS')) { console.log(green('Solution:\n\t' + 'fix your Sass code')) console.log('Line: ' + e.line) console.log('Column: ' + e.column) } if (e.message.includes('sass') && e.message.includes('find module')) { console.log(green('Solution:\n\t' + 'npm install --save-dev sass')) } if (e.message.includes('node-sass') && e.message.includes('bindings')) { console.log(green('Solution:\n\t' + 'npm rebuild node-sass --force')) } console.log() } } return { css: '', map: '' } } return { name: 'scss', intro() { return options.insert === true ? insertStyleFn.replace(/insertStyleFn/, insertStyleFnName) : '' }, async transform(code, id) { if (!filter(id)) { return } // Add the include path before doing any processing includePaths.push(dirname(id)) // Rebuild all scss files if anything happens to this folder // TODO: check if it's possible to get a list of all dependent scss files // and only watch those if (options.watch) { const files = Array.isArray(options.watch) ? options.watch : [options.watch] files.forEach(file => this.addWatchFile(file)) } if (options.insert === true) { // When the 'insert' is enabled, the stylesheet will be inserted into <head/> tag. const { css, map } = await compileToCSS(code) return { code: 'export default ' + insertStyleFnName + '(' + JSON.stringify(css) + ')', map: { mappings: '' } } } else if (options.output === false) { // When output is disabled, the stylesheet is exported as a string const { css, map } = await compileToCSS(code) return { code: 'export default ' + JSON.stringify(css), map: { mappings: '' } } } // Map of every stylesheet styles[id] = code return '' }, async generateBundle(opts) { // No stylesheet needed if (options.output === false || options.insert === true) { return } // Combine all stylesheets let scss = '' for (const id in styles) { scss += styles[id] || '' } if (typeof dest !== 'string') { // Guess destination filename dest = opts.file || 'bundle.js' if (dest.endsWith('.js')) { dest = dest.slice(0, -3) } dest = dest + '.css' } const compiled = await compileToCSS(scss) if (typeof compiled !== 'object' || typeof compiled.css !== 'string') { return } // Emit styles through callback if (typeof options.output === 'function') { options.output(compiled.css, styles) return } // Don't create unwanted empty stylesheets if (!compiled.css.length) { return } // Ensure that dest parent folders exist (create the missing ones) ensureParentDirsSync(dirname(dest)) // Emit styles to file writeFile(dest, compiled.css, err => { if (options.verbose !== false) { if (err) { console.error(red(err.toString())) } else if (compiled.css) { console.log(green(dest || '?'), getSize(compiled.css.length)) } } }) if (options.sourceMap && compiled.map) { let sourcemap = compiled.map if (typeof compiled.map.toString === 'function') { sourcemap = compiled.map.toString() } writeFile(dest + '.map', sourcemap, err => { if (options.verbose !== false && err) { console.error(red(err.toString())) } }) } } } } /** * Create a style tag and append to head tag * * @param {String} css style * @return {String} css style */ const insertStyleFn = `function insertStyleFn(css) { if (!css) { return } if (typeof window === 'undefined') { return } const style = document.createElement('style'); style.setAttribute('type', 'text/css'); style.innerHTML = css; document.head.appendChild(style); return css }` function loadSassLibrary(): SassRenderer { try { return require('sass') } catch (e) { return require('node-sass') } } function stringToCSS(input: string | CSS): MappedCSS { if (typeof input === 'string') { return { css: input, map: '' } } return input } function red(text: string) { return '\x1b[1m\x1b[31m' + text + '\x1b[0m' } function green(text: string) { return '\x1b[1m\x1b[32m' + text + '\x1b[0m' } function getSize(bytes: number) { return bytes < 10000 ? bytes.toFixed(0) + ' B' : bytes < 1024000 ? (bytes / 1024).toPrecision(3) + ' kB' : (bytes / 1024 / 1024).toPrecision(4) + ' MB' } function ensureParentDirsSync(dir: string) { if (existsSync(dir)) { return } try { mkdirSync(dir) } catch (err) { if (err.code === 'ENOENT') { ensureParentDirsSync(dirname(dir)) ensureParentDirsSync(dir) } } }
the_stack
import * as d3 from 'd3'; import * as React from 'react'; import { connect } from 'react-redux'; import IconCfg from '#app/components/IconPicker/iconCfg'; import Menu from '#app/modules/Explore/NebulaGraph/Menu'; import { IRootState } from '#app/store'; import { INode, IPath } from '#app/utils/interface'; import './index.less'; import Links from './Links'; import Labels from './NodeTexts'; import SelectIds from './SelectIds'; const mapState = (state: IRootState) => ({ offsetX: state.d3Graph.canvasOffsetX, offsetY: state.d3Graph.canvasOffsetY, isZoom: state.d3Graph.isZoom, scale: state.d3Graph.canvasScale, }); interface IProps extends ReturnType<typeof mapState> { width: number; height: number; data: { vertexes: INode[]; edges: IPath[]; }; showTagFields: string[]; showEdgeFields: string[]; selectedNodes: INode[]; selectedPaths: IPath[]; onSelectVertexes: (vertexes: INode[]) => void; onSelectEdges: (edges: IPath[]) => void; onMouseInNode: (node: INode, event: MouseEvent) => void; onMouseOut: () => void; onMouseInLink: (link: IPath, event: MouseEvent) => void; onDblClickNode: () => void; } class NebulaD3 extends React.Component<IProps> { nodeRef: SVGGElement; circleRef: SVGCircleElement; canvasBoardRef: SVGCircleElement; force: any; svg: any; node: any; link: any; linksText: any; nodeText: any; iconText: any; componentDidMount() { this.svg = d3.select('#output-graph'); const { offsetX, offsetY, scale } = this.props; this.initMarker(); d3.select('.nebula-d3-canvas').attr( 'transform', `translate(${offsetX},${offsetY}) scale(${scale})`, ); } initMarker = () => { const defs = this.svg.append('defs'); defs .append('marker') .attr('id', 'marker') .attr('markerUnits', 'userSpaceOnUse') .attr('viewBox', '-20 -10 20 20') .attr('refX', 20) .attr('refY', 0) .attr('orient', 'auto') .attr('markerWidth', 20) .attr('markerHeight', 20) .attr('xoverflow', 'visible') .append('path') .attr('d', 'M-10, -5 L 0,0 L -10, 5') .attr('fill', '#595959') .attr('stroke', '#595959'); defs .append('marker') .attr('id', 'marker-actived') .attr('markerUnits', 'userSpaceOnUse') .attr('viewBox', '-20 -10 20 20') .attr('refX', 25.5) .attr('refY', 0) .attr('orient', 'auto') .attr('markerWidth', 16) .attr('markerHeight', 16) .attr('xoverflow', 'visible') .append('path') .attr('d', 'M-16, -8 L 0,0 L -16, 8') .attr('fill', '#0091FF') .attr('stroke', '#0091FF') .attr('stroke-opacity', '0.6') .attr('fill-opacity', '0.9'); }; componentDidUpdate() { const { data, selectedNodes } = this.props; this.handleDeleteNodes(data.vertexes); this.handleUpdateNodes(data.vertexes, selectedNodes); this.handleUpdateIcons(data.vertexes); this.force.on('tick', () => this.tick()); } handleNodeClick = (d: any) => { const event = d3.event; const { selectedNodes, onSelectVertexes } = this.props; if (event.shiftKey) { const data = selectedNodes.find(n => n.name === d.name) ? selectedNodes.filter(n => n.name !== d.name) : [...selectedNodes, d]; onSelectVertexes(data); } else { onSelectVertexes([d]); } }; handleEdgeClick = (d: any) => { const event = d3.event; const { selectedPaths, onSelectEdges } = this.props; if (event.shiftKey) { const data = selectedPaths.find(n => n.id === d.id) ? selectedPaths.filter(n => n.id !== d.id) : [...selectedPaths, d]; onSelectEdges(data); } else { onSelectEdges([d]); } }; dragged = d => { d.fx = d3.event.x; d.fy = d3.event.y; d.isFixed = true; }; dragstart = (d: any) => { if (!d3.event.active) { this.force.alphaTarget(0.6).restart(); } return d; }; dragEnded = () => { if (!d3.event.active) { this.force.alphaTarget(0); } }; tick = () => { this.link.attr('d', (d: any) => { if (d.target.name === d.source.name) { const param = d.size > 1 ? 50 : 30; const dr = param / d.linknum; return ( 'M' + d.source.x + ',' + d.source.y + 'A' + dr + ',' + dr + ' 0 1,1 ' + d.target.x + ',' + (d.target.y + 1) ); } else if (d.size % 2 !== 0 && d.linknum === 1) { return ( 'M ' + d.source.x + ' ' + d.source.y + ' L ' + d.target.x + ' ' + d.target.y ); } const curve = 3; const homogeneous = 0.5; const dx = d.target.x - d.source.x; const dy = d.target.y - d.source.y; const dr = (Math.sqrt(dx * dx + dy * dy) * (d.linknum + homogeneous)) / (curve * homogeneous); if (d.linknum < 0) { const dr = (Math.sqrt(dx * dx + dy * dy) * (-1 * d.linknum + homogeneous)) / (curve * homogeneous); return ( 'M' + d.source.x + ',' + d.source.y + 'A' + dr + ',' + dr + ' 0 0,0 ' + d.target.x + ',' + d.target.y ); } return ( 'M' + d.source.x + ',' + d.source.y + 'A' + dr + ',' + dr + ' 0 0, 1 ' + d.target.x + ',' + d.target.y ); }); this.node.attr('cx', d => d.x).attr('cy', d => d.y); this.iconText?.attr('x', d => d.x).attr('y', d => d.y); d3.selectAll('.text') .attr('transform-origin', (d: any) => { return `${(d.source.x + d.target.x) / 2} ${(d.source.y + d.target.y) / 2}`; }) .attr('rotate', (d: any) => { if (d.source.x - d.target.x > 0) { return 180; } return 0; }); this.linksText .attr('x', (d: any) => { return (d.source.x + d.target.x) / 2; }) .attr('y', (d: any) => { return (d.source.y + d.target.y) / 2; }) .text((d: any) => { if (d.source.x - d.target.x > 0) { return ( this.edgeName(d) .join(' & ') .split('') .reverse() .join('') || d.type .split('') .reverse() .join('') ); } return this.edgeName(d).join(' & ') || d.type; }); this.nodeRenderText(); }; handleDeleteNodes(nodes: INode[]) { const currentNodes = d3.selectAll('.node'); if (nodes.length === 0) { currentNodes.remove(); return; } else if (currentNodes.size() > nodes.length) { const ids = nodes.map(i => i.name); const deleteNodes = currentNodes.filter((data: any) => { return !ids.includes(data.name); }); deleteNodes.remove(); return; } } handleUpdateNodes(nodes: INode[], selectNodes: INode[]) { const selectNodeIds = selectNodes.map(node => node.uuid); d3.select(this.nodeRef) .selectAll('circle') .data(nodes) .style('fill', (d: INode) => d.color) .classed('active', (d: INode) => selectNodeIds.includes(d.uuid)) .attr('id', (d: INode) => `circle-${d.uuid}`) .enter() .append<SVGGElement>('g') .attr('id', (d: INode) => `node_${d.uuid}`) .attr('class', 'node') .append<SVGCircleElement>('circle') .attr('class', 'circle') .attr('r', 20) .style('fill', (d: INode) => d.color) // HACK: Color distortion caused by delete node .on('mouseover', (d: INode) => { if (this.props.onMouseInNode) { this.props.onMouseInNode(d, d3.event); } }) .on('mouseout', () => { if (this.props.onMouseOut) { this.props.onMouseOut(); } }); d3.select(this.nodeRef) .selectAll('g') .data(nodes) .classed('active-node', (d: INode) => selectNodeIds.includes(d.uuid)); this.node = d3 .selectAll('.circle') .on('click', this.handleNodeClick) .on('dblclick', this.props.onDblClickNode) .call( d3 .drag() .on('start', d => this.dragstart(d)) .on('drag', d => this.dragged(d)) .on('end', this.dragEnded) as any, ); } handleUpdateIcons = (nodes: INode[]) => { nodes.forEach(a => { if ( a.icon && !d3 .select('#node_' + a.uuid) .select('.icon') .node() ) { d3.selectAll('#node_' + a.uuid) .append('text') .attr('class', 'icon') .attr('text-anchor', 'middle') .attr('dominant-baseline', 'central') .attr('stroke', 'black') .attr('stroke-width', '0.00001%') .attr('font-family', 'nebula-cloud-icon') .attr('x', (d: any) => d.x) .attr('y', (d: any) => d.y) .attr('id', (d: any) => d.uuid) .attr('font-size', '20px') .text(IconCfg.filter(icon => icon.type === a.icon)[0].content); } }); if (d3.selectAll('.icon').node()) { this.iconText = d3 .selectAll('.icon') .on('click', this.handleNodeClick) .on('dblclick', this.props.onDblClickNode) .call( d3 .drag() .on('start', d => this.dragstart(d)) .on('drag', d => this.dragged(d)) .on('end', this.dragEnded) as any, ); } }; handleUpdataNodeTexts = () => { if (this.force) { this.nodeText = d3 .selectAll('.label') .on('click', this.handleNodeClick) .on('mouseover', () => { if (this.props.onMouseOut) { this.props.onMouseOut(); } }) .call( d3 .drag() .on('start', d => this.dragstart(d)) .on('drag', d => this.dragged(d)) .on('end', this.dragEnded) as any, ); } }; handleUpdateLinks = () => { if (this.force) { this.link = d3.selectAll('.link').on('click', this.handleEdgeClick); d3.selectAll('.link:not(.active-link):not(.hovered-link)') .attr('marker-end', 'url(#marker)') .style('stroke', '#595959') .style('stroke-width', 2); d3.selectAll('.link.active-link') .attr('marker-end', 'url(#marker-actived)') .style('stroke', '#0091ff') .style('stroke-width', 3); this.linksText = d3 .selectAll('.text') .selectAll('.textPath') .attr(':href', (d: any) => '#text-path-' + d.uuid) .attr('startOffset', '50%'); } }; // compute to get (x,y ) of the nodes by d3-force: https://github.com/d3/d3-force/blob/v1.2.1/README.md#d3-force // it will change the data.edges and data.vertexes passed in computeDataByD3Force() { const { data } = this.props; const linkForce = d3 .forceLink(data.edges) .id((d: any) => { return d.name; }) .distance(210); if (!this.force) { this.force = d3 .forceSimulation() .force('charge', d3.forceManyBody().strength(-20)) .force( 'collide', d3 .forceCollide() .radius(35) .iterations(2), ); } this.force .nodes(data.vertexes) .force('link', linkForce) .restart(); } isIncludeField = (node, field) => { let isInclude = false; if (node.nodeProp && node.nodeProp.properties) { const properties = node.nodeProp.properties; isInclude = Object.keys(properties).some(v => { const valueObj = properties[v]; return Object.keys(valueObj).some( nodeField => field === v + '.' + nodeField, ); }); } return isInclude; }; edgeName = edge => { const { showEdgeFields } = this.props; const edgeText: any = []; if (showEdgeFields.includes(`${edge.type}.type`)) { if (showEdgeFields.includes(`${edge.type}._rank`)) { edgeText.push(`${edge.type}@${edge.rank}`); } else { edgeText.push(edge.type); } } showEdgeFields.forEach(field => { Object.keys(edge.edgeProp.properties).forEach(property => { if (field === `${edge.type}.${property}`) { edgeText.push(edge.edgeProp.properties[property]); } }); }); return edgeText; }; targetName = (node, field) => { let nodeText = ''; const properties = node.nodeProp.properties; Object.keys(properties).some(property => { const value = properties[property]; return Object.keys(value).some(nodeField => { const fieldStr = property + '.' + nodeField; if (fieldStr === field) { nodeText = `${value[nodeField]}`; return true; } }); }); return nodeText; }; nodeRenderText() { const { showTagFields, data } = this.props; d3.selectAll('tspan').remove(); data.vertexes.forEach((node: any) => { let line = 1; if (node.nodeProp) { showTagFields.forEach(field => { if (this.isIncludeField(node, field)) { line++; d3.select('#name_' + node.uuid) .append('tspan') .attr('x', (d: any) => d.x) .attr('y', (d: any) => d.y - 20 + 20 * line) .attr('dy', '1em') .text(d => this.targetName(d, field)); } }); } }); } iconRenderText() { const { data } = this.props; data.vertexes.forEach((node: any) => { if (node.nodeProp) { d3.select('#icon_' + node.uuid) .append('tspan') .attr('x', (d: any) => d.x) .attr('y', (d: any) => d.y) .attr('dy', '1em'); } }); } render() { this.computeDataByD3Force(); const { width, height, data, onMouseInLink, onMouseOut, offsetX, offsetY, scale, selectedPaths, onSelectVertexes, onSelectEdges, isZoom, } = this.props; return ( <> <svg id="output-graph" className={isZoom ? 'cursor-move' : undefined} width={width} height={height} > <g className="nebula-d3-canvas" ref={(ref: SVGCircleElement) => (this.canvasBoardRef = ref)} > <Links links={data.edges} selectedPaths={selectedPaths} onUpdateLinks={this.handleUpdateLinks} onMouseInLink={onMouseInLink} onMouseOut={onMouseOut} /> <g className="nebula-d3-nodes" ref={(ref: SVGGElement) => (this.nodeRef = ref)} /> <Labels nodes={data.vertexes} onUpDataNodeTexts={this.handleUpdataNodeTexts} /> </g> <SelectIds nodes={data.vertexes} links={data.edges} offsetX={offsetX} offsetY={offsetY} scale={scale} onSelectVertexes={onSelectVertexes} onSelectEdges={onSelectEdges} selectedPaths={selectedPaths} /> </svg> <Menu width={width} height={height} /> </> ); } } export default connect(mapState)(NebulaD3);
the_stack
declare module 'metro' { //#region metro/src/Assets.js type AssetDataWithoutFiles = { readonly __packager_asset: true; readonly fileSystemLocation: string; readonly hash: string; readonly height: number | null | undefined; readonly httpServerLocation: string; readonly name: string; readonly scales: number[]; readonly type: string; readonly width: number | null | undefined; }; export type AssetData = AssetDataWithoutFiles & { readonly files: string[] }; //#endregion //#region metro/src/DeltaBundler/types.flow.js type DynamicRequiresBehavior = unknown; type MinifierConfig = unknown; type BundleDetails = unknown; type GlobalCacheDisabledReason = unknown; type MixedSourceMap = unknown; type MetroSourceMapSegmentTuple = unknown; interface MixedOutput { readonly data: unknown; readonly type: string; } interface BabelSourceLocation { start: { line: number; column: number }; end: { line: number; column: number }; identifierName?: string; } interface TransformResultDependency { /** * The literal name provided to a require or import call. For example 'foo' in * case of `require('foo')`. */ readonly name: string; /** * Extra data returned by the dependency extractor. Whatever is added here is * blindly piped by Metro to the serializers. */ readonly data: { /** * If `true` this dependency is due to a dynamic `import()` call. If `false`, * this dependency was pulled using a synchronous `require()` call. */ readonly isAsync: boolean; /** * The dependency is actually a `__prefetchImport()` call. */ readonly isPrefetchOnly?: true; /** * The condition for splitting on this dependency edge. */ readonly splitCondition?: { readonly mobileConfigName: string; }; /** * The dependency is enclosed in a try/catch block. */ readonly isOptional?: boolean; readonly locs: readonly BabelSourceLocation[]; }; } interface Dependency { readonly absolutePath: string; readonly data: TransformResultDependency; } export interface Module<T = MixedOutput> { readonly dependencies: Map<string, Dependency>; readonly inverseDependencies: Set<string>; readonly output: readonly T[]; readonly path: string; readonly getSource: () => Buffer; } export interface Graph<T = MixedOutput> { dependencies: Map<string, Module<T>>; importBundleNames: Set<string>; readonly entryPoints: readonly string[]; } export type TransformResult<T = MixedOutput> = Readonly<{ dependencies: readonly TransformResultDependency[]; output: readonly T[]; }>; interface AllowOptionalDependenciesWithOptions { readonly exclude: string[]; } type AllowOptionalDependencies = boolean | AllowOptionalDependenciesWithOptions; export interface DeltaResult<T = MixedOutput> { readonly added: Map<string, Module<T>>; readonly modified: Map<string, Module<T>>; readonly deleted: Set<string>; readonly reset: boolean; } export interface SerializerOptions { readonly asyncRequireModulePath: string; readonly createModuleId: (arg0: string) => number; readonly dev: boolean; readonly getRunModuleStatement: (arg0: number | string) => string; readonly inlineSourceMap: boolean | null | undefined; readonly modulesOnly: boolean; readonly processModuleFilter: (module: Module) => boolean; readonly projectRoot: string; readonly runBeforeMainModule: readonly string[]; readonly runModule: boolean; readonly sourceMapUrl: string | null | undefined; readonly sourceUrl: string | null | undefined; } //#endregion //#region metro/src/DeltaBundler/Serializers/getRamBundleInfo.js interface RamBundleInfo { getDependencies: (filePath: string) => Set<string>; startupModules: readonly ModuleTransportLike[]; lazyModules: readonly ModuleTransportLike[]; groups: Map<number, Set<number>>; } //#endregion //#region metro/src/index.js import { Server as HttpServer, IncomingMessage, ServerResponse } from 'http'; import { Server as HttpsServer } from 'https'; import { ConfigT, InputConfigT, Middleware, loadConfig } from 'metro-config'; type MetroMiddleWare = { attachHmrServer: (httpServer: HttpServer | HttpsServer) => void; end: () => void; metroServer: Server; middleware: Middleware; }; type RunServerOptions = { hasReducedPerformance?: boolean; hmrEnabled?: boolean; host?: string; onError?: (arg0: Error & { code?: string }) => void; onReady?: (server: HttpServer | HttpsServer) => void; runInspectorProxy?: boolean; secure?: boolean; secureCert?: string; secureKey?: string; }; type BuildGraphOptions = { entries: readonly string[]; customTransformOptions?: CustomTransformOptions; dev?: boolean; minify?: boolean; onProgress?: (transformedFileCount: number, totalFileCount: number) => void; platform?: string; type?: 'module' | 'script'; }; type RunBuildOptions = { entry: string; dev?: boolean; out?: string; onBegin?: () => void; onComplete?: () => void; onProgress?: (transformedFileCount: number, totalFileCount: number) => void; minify?: boolean; output?: { build: ( arg0: Server, arg1: RequestOptions ) => Promise<{ code: string; map: string; }>; save: ( arg0: { code: string; map: string; }, arg1: OutputOptions, arg2: (...args: string[]) => void ) => Promise<unknown>; }; platform?: string; sourceMap?: boolean; sourceMapUrl?: string; }; export function runMetro(config: InputConfigT, options?: ServerOptions): Promise<Server>; export { loadConfig }; export function createConnectMiddleware( config: ConfigT, options?: ServerOptions ): Promise<MetroMiddleWare>; export function runServer( config: ConfigT, options: RunServerOptions ): Promise<HttpServer | HttpsServer>; export function runBuild( config: ConfigT, options: RunBuildOptions ): Promise<{ code: string; map: string; }>; export function buildGraph(config: InputConfigT, options: BuildGraphOptions): Promise<Graph>; //#endregion //#region metro/src/JSTransformer/worker.js type CustomTransformOptions = { [key: string]: unknown; }; export type JsTransformerConfig = Readonly<{ assetPlugins: readonly string[]; assetRegistryPath: string; asyncRequireModulePath: string; babelTransformerPath: string; dynamicDepsInPackages: DynamicRequiresBehavior; enableBabelRCLookup: boolean; enableBabelRuntime: boolean; experimentalImportBundleSupport: boolean; minifierConfig: MinifierConfig; minifierPath: string; optimizationSizeLimit: number; publicPath: string; allowOptionalDependencies: AllowOptionalDependencies; }>; //#endregion //#region metro/src/lib/reporting.js /** * A tagged union of all the actions that may happen and we may want to * report to the tool user. */ export type ReportableEvent = | { port: number; hasReducedPerformance: boolean; type: 'initialize_started'; } | { type: 'initialize_failed'; port: number; error: Error; } | { buildID: string; type: 'bundle_build_done'; } | { buildID: string; type: 'bundle_build_failed'; } | { buildID: string; bundleDetails: BundleDetails; type: 'bundle_build_started'; } | { error: Error; type: 'bundling_error'; } | { type: 'dep_graph_loading'; hasReducedPerformance: boolean; } | { type: 'dep_graph_loaded' } | { buildID: string; type: 'bundle_transform_progressed'; transformedFileCount: number; totalFileCount: number; } | { type: 'global_cache_error'; error: Error; } | { type: 'global_cache_disabled'; reason: GlobalCacheDisabledReason; } | { type: 'transform_cache_reset' } | { type: 'worker_stdout_chunk'; chunk: string; } | { type: 'worker_stderr_chunk'; chunk: string; } | { type: 'hmr_client_error'; error: Error; } | { type: 'client_log'; level: | 'trace' | 'info' | 'warn' | 'log' | 'group' | 'groupCollapsed' | 'groupEnd' | 'debug'; data: unknown[]; }; /** * Code across the application takes a reporter as an option and calls the * update whenever one of the ReportableEvent happens. Code does not directly * write to the standard output, because a build would be: * * 1. ad-hoc, embedded into another tool, in which case we do not want to * pollute that tool's own output. The tool is free to present the * warnings/progress we generate any way they want, by specifing a custom * reporter. * 2. run as a background process from another tool, in which case we want * to expose updates in a way that is easily machine-readable, for example * a JSON-stream. We don't want to pollute it with textual messages. * * We centralize terminal reporting into a single place because we want the * output to be robust and consistent. The most common reporter is * TerminalReporter, that should be the only place in the application should * access the `terminal` module (nor the `console`). */ export interface Reporter { update(event: ReportableEvent): void; } //#endregion //#region metro/src/ModuleGraph/types.flow.js export type TransformVariants = { readonly [name: string]: object; }; //#endregion //#region metro/src/Server.js type ServerOptions = Readonly<{ watch?: boolean; }>; //#endregion //#region metro/src/Server/index.js type IncrementalBundler = unknown; export class Server { constructor(config: ConfigT, options?: ServerOptions); end(): void; getBundler(): IncrementalBundler; getCreateModuleId(): (path: string) => number; build(options: BundleOptions): Promise<{ code: string; map: string; }>; getRamBundleInfo(options: BundleOptions): Promise<RamBundleInfo>; getAssets(options: BundleOptions): Promise<readonly AssetData[]>; getOrderedDependencyPaths(options: { readonly dev: boolean; readonly entryFile: string; readonly minify: boolean; readonly platform: string; }): Promise<string[]>; processRequest( req: IncomingMessage, res: ServerResponse, next: (arg0: Error | null | undefined) => unknown ): void; getNewBuildID(): string; getPlatforms(): readonly string[]; getWatchFolders(): readonly string[]; static DEFAULT_GRAPH_OPTIONS: { customTransformOptions: any; dev: boolean; hot: boolean; minify: boolean; }; static DEFAULT_BUNDLE_OPTIONS: typeof Server.DEFAULT_GRAPH_OPTIONS & { excludeSource: false; inlineSourceMap: false; modulesOnly: false; onProgress: null; runModule: true; shallow: false; sourceMapUrl: null; sourceUrl: null; }; } //#endregion //#region metro/src/shared/types.flow.js type BundleType = 'bundle' | 'delta' | 'meta' | 'map' | 'ram' | 'cli' | 'hmr' | 'todo' | 'graph'; type MetroSourceMapOrMappings = MixedSourceMap | MetroSourceMapSegmentTuple[]; export interface BundleOptions { bundleType: BundleType; customTransformOptions: CustomTransformOptions; dev: boolean; entryFile: string; readonly excludeSource: boolean; readonly hot: boolean; readonly inlineSourceMap: boolean; minify: boolean; readonly modulesOnly: boolean; onProgress: (doneCont: number, totalCount: number) => unknown | null | undefined; readonly platform: string | null | undefined; readonly runModule: boolean; readonly shallow: boolean; sourceMapUrl: string | null | undefined; sourceUrl: string | null | undefined; createModuleIdFactory?: () => (path: string) => number; } type ModuleTransportLike = { readonly code: string; readonly id: number; readonly map: MetroSourceMapOrMappings | null | undefined; readonly name?: string; readonly sourcePath: string; }; export interface OutputOptions { bundleOutput: string; bundleEncoding?: 'utf8' | 'utf16le' | 'ascii'; dev?: boolean; indexedRamBundle?: boolean; platform: string; sourcemapOutput?: string; sourcemapSourcesRoot?: string; sourcemapUseAbsolutePath?: boolean; } export interface RequestOptions { entryFile: string; inlineSourceMap?: boolean; sourceMapUrl?: string; dev?: boolean; minify: boolean; platform: string; createModuleIdFactory?: () => (path: string) => number; onProgress?: (transformedFileCount: number, totalFileCount: number) => void; } //#endregion }
the_stack
import { fakeAsync, TestBed, tick, flush, waitForAsync } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { IgxTooltipModule, IgxTooltipTargetDirective, IgxTooltipDirective } from './tooltip.directive'; import { IgxTooltipSingleTargetComponent, IgxTooltipMultipleTargetsComponent } from '../../test-utils/tooltip-components.spec'; import { UIInteractions } from '../../test-utils/ui-interactions.spec'; import { configureTestSuite } from '../../test-utils/configure-suite'; import { HorizontalAlignment, VerticalAlignment, AutoPositionStrategy } from '../../services/public_api'; const HIDDEN_TOOLTIP_CLASS = 'igx-tooltip--hidden'; const TOOLTIP_CLASS = 'igx-tooltip--desktop'; describe('IgxTooltip', () => { configureTestSuite(); let fix; let tooltipNativeElement; let tooltipTarget: IgxTooltipTargetDirective; let button; beforeAll(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ IgxTooltipSingleTargetComponent, IgxTooltipMultipleTargetsComponent ], imports: [NoopAnimationsModule, IgxTooltipModule] }).compileComponents(); UIInteractions.clearOverlay(); })); afterEach(() => { UIInteractions.clearOverlay(); }); describe('Single target with single tooltip', () => { // configureTestSuite(); beforeEach(waitForAsync(() => { fix = TestBed.createComponent(IgxTooltipSingleTargetComponent); fix.detectChanges(); tooltipNativeElement = fix.debugElement.query(By.directive(IgxTooltipDirective)).nativeElement; tooltipTarget = fix.componentInstance.tooltipTarget as IgxTooltipTargetDirective; button = fix.debugElement.query(By.directive(IgxTooltipTargetDirective)); })); it('IgxTooltipTargetDirective default values', () => { expect(tooltipTarget.showDelay).toBe(500); expect(tooltipTarget.hideDelay).toBe(500); expect(tooltipTarget.tooltipDisabled).toBe(false); expect(tooltipTarget.overlaySettings).toBeUndefined(); }); it('IgxTooltipTargetDirective updated values', () => { tooltipTarget.showDelay = 740; fix.detectChanges(); expect(tooltipTarget.showDelay).toBe(740); tooltipTarget.hideDelay = 725; fix.detectChanges(); expect(tooltipTarget.hideDelay).toBe(725); tooltipTarget.tooltipDisabled = true; fix.detectChanges(); expect(tooltipTarget.tooltipDisabled).toBe(true); }); it('IgxTooltip is initially hidden', () => { verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); }); it('IgxTooltip is shown/hidden when hovering/unhovering its target', fakeAsync(() => { hoverElement(button); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); unhoverElement(button); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); })); it('verify tooltip default position', fakeAsync(() => { hoverElement(button); flush(); verifyTooltipPosition(tooltipNativeElement, button, true); })); it('IgxTooltip is not shown when is disabled and hovering its target', fakeAsync(() => { tooltipTarget.tooltipDisabled = true; fix.detectChanges(); hoverElement(button); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); tooltipTarget.tooltipDisabled = false; fix.detectChanges(); hoverElement(button); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); })); it('IgxTooltip mouse interaction respects showDelay', fakeAsync(() => { tooltipTarget.showDelay = 900; fix.detectChanges(); hoverElement(button); tick(500); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); tick(300); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); tick(100); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); })); it('IgxTooltip mouse interaction respects hideDelay', fakeAsync(() => { tooltipTarget.hideDelay = 700; fix.detectChanges(); hoverElement(button); flush(); unhoverElement(button); tick(400); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); tick(100); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); tick(200); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); })); it('IgxTooltip is shown/hidden when invoking respective API methods', fakeAsync(() => { tooltipTarget.showTooltip(); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); tooltipTarget.hideTooltip(); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); })); it('showing tooltip through API respects showDelay', fakeAsync(() => { tooltipTarget.showDelay = 400; fix.detectChanges(); tooltipTarget.showTooltip(); tick(300); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); tick(100); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); })); it('hiding tooltip through API respects hideDelay', fakeAsync(() => { tooltipTarget.hideDelay = 450; fix.detectChanges(); tooltipTarget.showTooltip(); flush(); tooltipTarget.hideTooltip(); tick(400); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); tick(50); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); })); it('IgxTooltip closes and reopens if it was opened through API and then its target is hovered', fakeAsync(() => { tooltipTarget.showTooltip(); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); hoverElement(button); tick(250); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); tick(250); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); })); it('IgxTooltip closes and reopens if opening it through API multiple times', fakeAsync(() => { tooltipTarget.showTooltip(); tick(500); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); tooltipTarget.showTooltip(); tick(250); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); tick(250); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); })); it('IgxTooltip respects the passed overlaySettings', fakeAsync(() => { // Hover the button. hoverElement(button); flush(); // Verify default position of the tooltip. verifyTooltipPosition(tooltipNativeElement, button, true); unhoverElement(button); flush(); // Use custom overlaySettings. tooltipTarget.overlaySettings = /*<OverlaySettings>*/ { target: tooltipTarget.nativeElement, positionStrategy: new AutoPositionStrategy({ horizontalStartPoint: HorizontalAlignment.Right, verticalStartPoint: VerticalAlignment.Bottom, horizontalDirection: HorizontalAlignment.Right, verticalDirection: VerticalAlignment.Bottom }) }; fix.detectChanges(); // Hover the button again. hoverElement(button); flush(); // Verify that the position of the tooltip is changed. verifyTooltipPosition(tooltipNativeElement, button, false); const targetRect = tooltipTarget.nativeElement.getBoundingClientRect(); const tooltipRect = tooltipNativeElement.getBoundingClientRect(); expect(Math.abs(tooltipRect.top - targetRect.bottom) <= 0.5).toBe(true); expect(Math.abs(tooltipRect.left - targetRect.right) <= 0.5).toBe(true); unhoverElement(button); flush(); })); it('IgxTooltip closes when the target is clicked', fakeAsync(() => { hoverElement(button); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); UIInteractions.simulateClickAndSelectEvent(button); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); })); it('IgxTooltip hides on pressing \'escape\' key', fakeAsync(() => { tooltipTarget.showTooltip(); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); UIInteractions.triggerKeyDownEvtUponElem('Escape', document.documentElement); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); })); describe('Tooltip events', () => { // configureTestSuite(); it('should emit the proper events when hovering/unhovering target', fakeAsync(() => { spyOn(tooltipTarget.tooltipShow, 'emit'); spyOn(tooltipTarget.tooltipHide, 'emit'); hoverElement(button); expect(tooltipTarget.tooltipShow.emit).toHaveBeenCalled(); flush(); unhoverElement(button); tick(500); expect(tooltipTarget.tooltipHide.emit).toHaveBeenCalled(); flush(); })); it('should emit the proper events when showing/hiding tooltip through API', fakeAsync(() => { spyOn(tooltipTarget.tooltipShow, 'emit'); spyOn(tooltipTarget.tooltipHide, 'emit'); tooltipTarget.showTooltip(); expect(tooltipTarget.tooltipShow.emit).toHaveBeenCalled(); flush(); tooltipTarget.hideTooltip(); tick(500); expect(tooltipTarget.tooltipHide.emit).toHaveBeenCalled(); flush(); })); it('should emit the proper events with correct eventArgs when hover/unhover', fakeAsync(() => { spyOn(tooltipTarget.tooltipShow, 'emit'); spyOn(tooltipTarget.tooltipHide, 'emit'); const tooltipShowArgs = { target: tooltipTarget, tooltip: fix.componentInstance.tooltip, cancel: false }; const tooltipHideArgs = { target: tooltipTarget, tooltip: fix.componentInstance.tooltip, cancel: false }; hoverElement(button); expect(tooltipTarget.tooltipShow.emit).toHaveBeenCalledWith(tooltipShowArgs); flush(); unhoverElement(button); tick(500); expect(tooltipTarget.tooltipHide.emit).toHaveBeenCalledWith(tooltipHideArgs); flush(); })); it('should emit the proper events with correct eventArgs when show/hide through API', fakeAsync(() => { spyOn(tooltipTarget.tooltipShow, 'emit'); spyOn(tooltipTarget.tooltipHide, 'emit'); const tooltipShowArgs = { target: tooltipTarget, tooltip: fix.componentInstance.tooltip, cancel: false }; const tooltipHideArgs = { target: tooltipTarget, tooltip: fix.componentInstance.tooltip, cancel: false }; tooltipTarget.showTooltip(); expect(tooltipTarget.tooltipShow.emit).toHaveBeenCalledWith(tooltipShowArgs); flush(); tooltipTarget.hideTooltip(); tick(500); expect(tooltipTarget.tooltipHide.emit).toHaveBeenCalledWith(tooltipHideArgs); flush(); })); it('should cancel the showing event when hover', fakeAsync(() => { fix.componentInstance.cancelShowing = true; hoverElement(button); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); })); it('should cancel the hiding event when unhover', fakeAsync(() => { fix.componentInstance.cancelHiding = true; hoverElement(button); flush(); unhoverElement(button); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); })); it('should cancel the showing event when show through API', fakeAsync(() => { fix.componentInstance.cancelShowing = true; tooltipTarget.showTooltip(); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); })); it('should cancel the hiding event when hide through API', fakeAsync(() => { fix.componentInstance.cancelHiding = true; tooltipTarget.showTooltip(); flush(); tooltipTarget.hideTooltip(); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); })); }); describe('Tooltip touch', () => { // configureTestSuite(); it('IgxTooltip is shown/hidden when touching/untouching its target', fakeAsync(() => { touchElement(button); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); const dummyDiv = fix.debugElement.query(By.css('.dummyDiv')); touchElement(dummyDiv); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); })); it('IgxTooltip is not shown when is disabled and touching its target', fakeAsync(() => { tooltipTarget.tooltipDisabled = true; fix.detectChanges(); touchElement(button); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); tooltipTarget.tooltipDisabled = false; fix.detectChanges(); touchElement(button); flush(); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); })); it('IgxTooltip touch interaction respects showDelay', fakeAsync(() => { tooltipTarget.showDelay = 900; fix.detectChanges(); touchElement(button); tick(500); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); tick(300); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); tick(100); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); })); it('IgxTooltip touch interaction respects hideDelay', fakeAsync(() => { tooltipTarget.hideDelay = 700; fix.detectChanges(); touchElement(button); flush(); const dummyDiv = fix.debugElement.query(By.css('.dummyDiv')); touchElement(dummyDiv); tick(400); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); tick(100); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, true); tick(200); verifyTooltipVisibility(tooltipNativeElement, tooltipTarget, false); })); }); }); describe('Multiple targets with single tooltip', () => { // configureTestSuite(); let targetOne: IgxTooltipTargetDirective; let targetTwo: IgxTooltipTargetDirective; let buttonOne; let buttonTwo; beforeEach(waitForAsync(() => { fix = TestBed.createComponent(IgxTooltipMultipleTargetsComponent); fix.detectChanges(); tooltipNativeElement = fix.debugElement.query(By.directive(IgxTooltipDirective)).nativeElement; targetOne = fix.componentInstance.targetOne as IgxTooltipTargetDirective; targetTwo = fix.componentInstance.targetTwo as IgxTooltipTargetDirective; buttonOne = fix.debugElement.query(By.css('.buttonOne')); buttonTwo = fix.debugElement.query(By.css('.buttonTwo')); })); it('Same tooltip shows on different targets depending on which target is hovered', fakeAsync(() => { hoverElement(buttonOne); flush(); // Tooltip is positioned relative to buttonOne and NOT relative to buttonTwo verifyTooltipVisibility(tooltipNativeElement, targetOne, true); verifyTooltipPosition(tooltipNativeElement, buttonOne, true); verifyTooltipPosition(tooltipNativeElement, buttonTwo, false); unhoverElement(buttonOne); flush(); hoverElement(buttonTwo); flush(); // Tooltip is positioned relative to buttonTwo and NOT relative to buttonOne verifyTooltipVisibility(tooltipNativeElement, targetTwo, true); verifyTooltipPosition(tooltipNativeElement, buttonTwo, true); verifyTooltipPosition(tooltipNativeElement, buttonOne, false); })); it('Same tooltip shows on a second target when hovering it without closing from first target\'s logic', fakeAsync(() => { targetOne.hideDelay = 700; fix.detectChanges(); hoverElement(buttonOne); flush(); unhoverElement(buttonOne); tick(300); hoverElement(buttonTwo); tick(500); // Tooltip is visible and positioned relative to buttonTwo // and it was not closed due to buttonOne mouseLeave logic. verifyTooltipVisibility(tooltipNativeElement, targetTwo, true); verifyTooltipPosition(tooltipNativeElement, buttonTwo, true); verifyTooltipPosition(tooltipNativeElement, buttonOne, false); flush(); })); it('Hovering first target briefly and then hovering second target leads to tooltip showing for second target', fakeAsync(() => { targetOne.showDelay = 600; fix.detectChanges(); hoverElement(buttonOne); tick(400); verifyTooltipVisibility(tooltipNativeElement, targetOne, false); verifyTooltipPosition(tooltipNativeElement, buttonOne, false); unhoverElement(buttonOne); tick(100); hoverElement(buttonTwo); flush(); // Tooltip is visible and positioned relative to buttonTwo verifyTooltipVisibility(tooltipNativeElement, targetTwo, true); verifyTooltipPosition(tooltipNativeElement, buttonTwo, true); // Tooltip is NOT visible and positioned relative to buttonOne verifyTooltipPosition(tooltipNativeElement, buttonOne, false); })); }); }); const hoverElement = (element) => element.nativeElement.dispatchEvent(new MouseEvent('mouseenter')); const unhoverElement = (element) => element.nativeElement.dispatchEvent(new MouseEvent('mouseleave')); const touchElement = (element) => element.nativeElement.dispatchEvent(new TouchEvent('touchstart', { bubbles: true })); const verifyTooltipVisibility = (tooltipNativeElement, tooltipTarget, shouldBeVisible: boolean) => { if (shouldBeVisible) { expect(tooltipNativeElement.classList.contains(TOOLTIP_CLASS)).toBe(true); expect(tooltipNativeElement.classList.contains(HIDDEN_TOOLTIP_CLASS)).toBe(false); expect(tooltipTarget.tooltipHidden).toBe(false); } else { expect(tooltipNativeElement.classList.contains(TOOLTIP_CLASS)).toBe(false); expect(tooltipNativeElement.classList.contains(HIDDEN_TOOLTIP_CLASS)).toBe(true); expect(tooltipTarget.tooltipHidden).toBe(true); } }; const verifyTooltipPosition = (tooltipNativeElement, actualTarget, shouldBeAligned: boolean) => { const targetRect = actualTarget.nativeElement.getBoundingClientRect(); const tooltipRect = tooltipNativeElement.getBoundingClientRect(); const targetRectMidX = targetRect.left + targetRect.width / 2; const tooltipRectMidX = tooltipRect.left + tooltipRect.width / 2; const horizontalOffset = Math.abs(targetRectMidX - tooltipRectMidX); const verticalOffset = tooltipRect.top - targetRect.bottom; if (shouldBeAligned) { // Verify that tooltip and target are horizontally aligned with approximately same center expect(horizontalOffset >= 0).toBe(true, 'tooltip and target are horizontally MISaligned'); expect(horizontalOffset <= 0.5).toBe(true, 'tooltip and target are horizontally MISaligned'); // Verify that tooltip is vertically aligned beneath the target expect(verticalOffset >= 0).toBe(true, 'tooltip and target are vertically MISaligned'); expect(verticalOffset <= 6).toBe(true, 'tooltip and target are vertically MISaligned'); } else { // Verify that tooltip and target are NOT horizontally aligned with approximately same center expect(horizontalOffset > 0.1).toBe(true, 'tooltip and target are horizontally aligned'); } };
the_stack
import { InputNumber } from 'antd'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import * as Styled from './box-editor.style'; import * as typings from './box-editor.type'; export class BoxEditor extends React.Component<typings.Props, typings.State> { public static defaultProps = new typings.Props(); public state = new typings.State(); // 上一次鼠标 x, y 位置 private lastX: number = null as any; private lastY: number = null as any; // 当前按住的类型 private currentHolding: typings.MarginPaddingField = ''; // 记录鼠标是否按下了 private hasMouseDown = false; public componentWillMount() { this.init(this.props); } public componentWillReceiveProps(nextProps: typings.Props) { this.init(nextProps); } public componentDidMount() { document.addEventListener('mousemove', this.handleMouseMove); document.addEventListener('mouseup', this.handleMouseUp); } public componentWillUnmount() { document.removeEventListener('mousemove', this.handleMouseMove); document.removeEventListener('mouseup', this.handleMouseUp); } public render() { const normalBorderWidth = this.props.size / 4; const specialBorderWidth = this.props.size / 7; const containerStyle = { width: this.props.size, height: this.props.size - this.props.size / 5, }; const leftStyle = { left: specialBorderWidth, top: this.props.size / 2 - normalBorderWidth - this.props.size / 10, }; const topStyle = { top: specialBorderWidth, left: this.props.size / 2 - normalBorderWidth, }; const rightStyle = { right: specialBorderWidth, top: this.props.size / 2 - normalBorderWidth - this.props.size / 10, }; const bottomStyle = { bottom: specialBorderWidth, left: this.props.size / 2 - normalBorderWidth, }; const numberOuterLeftStyle = { width: specialBorderWidth, height: specialBorderWidth, left: 0, top: this.props.size / 2 - specialBorderWidth / 2 - this.props.size / 10, }; const numberOuterTopStyle = { width: specialBorderWidth, height: specialBorderWidth, top: 0, left: this.props.size / 2 - specialBorderWidth / 2, }; const numberOuterRightStyle = { width: specialBorderWidth, height: specialBorderWidth, right: 0, top: this.props.size / 2 - specialBorderWidth / 2 - this.props.size / 10, }; const numberOuterBottomStyle = { width: specialBorderWidth, height: specialBorderWidth, bottom: 0, left: this.props.size / 2 - specialBorderWidth / 2, }; const numberInnerLeftStyle = { width: specialBorderWidth, height: specialBorderWidth, left: this.props.size / 3 - specialBorderWidth / 2, top: this.props.size / 2 - specialBorderWidth / 2 - this.props.size / 10, }; const numberInnerTopStyle = { width: specialBorderWidth, height: specialBorderWidth, top: this.props.size / 3 - specialBorderWidth / 2, left: this.props.size / 2 - specialBorderWidth / 2, }; const numberInnerRightStyle = { width: specialBorderWidth, height: specialBorderWidth, right: this.props.size / 3 - specialBorderWidth / 2, top: this.props.size / 2 - specialBorderWidth / 2 - this.props.size / 10, }; const numberInnerBottomStyle = { width: specialBorderWidth, height: specialBorderWidth, bottom: this.props.size / 3 - specialBorderWidth / 2, left: this.props.size / 2 - specialBorderWidth / 2, }; return ( <Styled.Container style={containerStyle}> <Styled.Left style={leftStyle}> {this.renderTriangle('right', 'marginLeft')} {this.renderTriangle('right', 'paddingLeft', { marginLeft: 5 })} </Styled.Left> <Styled.Right style={rightStyle}> {this.renderTriangle('left', 'paddingRight')} {this.renderTriangle('left', 'marginRight', { marginLeft: 5 })} </Styled.Right> <Styled.Top style={topStyle}> {this.renderTriangle('bottom', 'marginTop')} {this.renderTriangle('bottom', 'paddingTop', { marginTop: 5 })} </Styled.Top> <Styled.Bottom style={bottomStyle}> {this.renderTriangle('top', 'paddingBottom')} {this.renderTriangle('top', 'marginBottom', { marginTop: 5 })} </Styled.Bottom> <Styled.NumberBox style={numberOuterLeftStyle}> <Styled.Input onMouseEnter={this.handleInputEnter.bind(this, 'marginLeft')} onMouseLeave={this.handleInputLeave.bind(this, 'marginLeft')} onChange={this.handleChange.bind(this, 'marginLeft')} value={this.state.marginLeft.toString()} /> </Styled.NumberBox> <Styled.NumberBox style={numberOuterTopStyle}> <Styled.Input onMouseEnter={this.handleInputEnter.bind(this, 'marginTop')} onMouseLeave={this.handleInputLeave.bind(this, 'marginTop')} onChange={this.handleChange.bind(this, 'marginTop')} value={this.state.marginTop.toString()} /> </Styled.NumberBox> <Styled.NumberBox style={numberOuterRightStyle}> <Styled.Input onMouseEnter={this.handleInputEnter.bind(this, 'marginRight')} onMouseLeave={this.handleInputLeave.bind(this, 'marginRight')} onChange={this.handleChange.bind(this, 'marginRight')} value={this.state.marginRight.toString()} /> </Styled.NumberBox> <Styled.NumberBox style={numberOuterBottomStyle}> <Styled.Input onMouseEnter={this.handleInputEnter.bind(this, 'marginBottom')} onMouseLeave={this.handleInputLeave.bind(this, 'marginBottom')} onChange={this.handleChange.bind(this, 'marginBottom')} value={this.state.marginBottom.toString()} /> </Styled.NumberBox> <Styled.NumberBox style={numberInnerLeftStyle}> <Styled.Input onMouseEnter={this.handleInputEnter.bind(this, 'paddingLeft')} onMouseLeave={this.handleInputLeave.bind(this, 'paddingLeft')} onChange={this.handleChange.bind(this, 'paddingLeft')} value={this.state.paddingLeft.toString()} /> </Styled.NumberBox> <Styled.NumberBox style={numberInnerTopStyle}> <Styled.Input onMouseEnter={this.handleInputEnter.bind(this, 'paddingTop')} onMouseLeave={this.handleInputLeave.bind(this, 'paddingTop')} onChange={this.handleChange.bind(this, 'paddingTop')} value={this.state.paddingTop.toString()} /> </Styled.NumberBox> <Styled.NumberBox style={numberInnerRightStyle}> <Styled.Input onMouseEnter={this.handleInputEnter.bind(this, 'paddingRight')} onMouseLeave={this.handleInputLeave.bind(this, 'paddingRight')} onChange={this.handleChange.bind(this, 'paddingRight')} value={this.state.paddingRight.toString()} /> </Styled.NumberBox> <Styled.NumberBox style={numberInnerBottomStyle}> <Styled.Input onMouseEnter={this.handleInputEnter.bind(this, 'paddingBottom')} onMouseLeave={this.handleInputLeave.bind(this, 'paddingBottom')} onChange={this.handleChange.bind(this, 'paddingBottom')} value={this.state.paddingBottom.toString()} /> </Styled.NumberBox> </Styled.Container> ); } /** * 初始化值 */ private init = (props: typings.Props) => { this.setState({ paddingLeft: props.paddingLeft, paddingTop: props.paddingTop, paddingRight: props.paddingRight, paddingBottom: props.paddingBottom, marginLeft: props.marginLeft, marginTop: props.marginTop, marginRight: props.marginRight, marginBottom: props.marginBottom, }); }; /** * 鼠标按下 */ private handleMouseDown = (name: typings.MarginPaddingField, event: MouseEvent) => { this.lastX = event.clientX; this.lastY = event.clientY; this.currentHolding = name; this.hasMouseDown = true; this.props.onStart(); }; /** * 鼠标移动监听处理 */ private handleMouseMove = (event: MouseEvent) => { const diffX = event.clientX - this.lastX; const diffY = event.clientY - this.lastY; switch (this.currentHolding) { case 'marginLeft': this.setState(state => ({ marginLeft: state.marginLeft - diffX, })); this.props.onChange(this.currentHolding, this.state.marginLeft); break; case 'paddingLeft': this.setState(state => ({ paddingLeft: state.paddingLeft - diffX, })); this.props.onChange(this.currentHolding, this.state.paddingLeft); break; case 'marginRight': this.setState(state => ({ marginRight: state.marginRight + diffX, })); this.props.onChange(this.currentHolding, this.state.marginRight); break; case 'paddingRight': this.setState(state => ({ paddingRight: state.paddingRight + diffX, })); this.props.onChange(this.currentHolding, this.state.paddingRight); break; case 'marginTop': this.setState(state => ({ marginTop: state.marginTop - diffY, })); this.props.onChange(this.currentHolding, this.state.marginTop); break; case 'paddingTop': this.setState(state => ({ paddingTop: state.paddingTop - diffY, })); this.props.onChange(this.currentHolding, this.state.paddingTop); break; case 'marginBottom': this.setState(state => ({ marginBottom: state.marginBottom + diffY, })); this.props.onChange(this.currentHolding, this.state.marginBottom); break; case 'paddingBottom': this.setState(state => ({ paddingBottom: state.paddingBottom + diffY, })); this.props.onChange(this.currentHolding, this.state.paddingBottom); break; default: } this.lastX = event.clientX; this.lastY = event.clientY; }; /** * 鼠标松开 */ private handleMouseUp = () => { if (!this.hasMouseDown) { return; } this.hasMouseDown = false; // 清空前,调用低频修改 this.props.onFinalChange(this.currentHolding, (this.state as any)[this.currentHolding]); this.currentHolding = ''; }; /** * 输入框调用的修改 */ private handleChange = (name: typings.MarginPaddingField, event: any) => { const value = Number(event.target.value) || 0; this.setState({ [name]: value, }); this.props.onChange(name, value); this.props.onFinalChange(name, value); }; private renderTriangle = (position: string, name: string, extendStyle: React.CSSProperties = {}) => { const style: React.CSSProperties = { ...extendStyle, width: 0, height: 0, }; const outerStyle: React.CSSProperties = {}; const normalBorderWidth = this.props.size / 4; const specialBorderWidth = this.props.size / 5; const outerWidth = this.props.size / 20; const outerSpace = this.props.size / 40; switch (position) { case 'left': style.borderTop = `${normalBorderWidth}px solid transparent`; style.borderBottom = `${normalBorderWidth}px solid transparent`; style.borderRightStyle = 'solid'; style.borderRightWidth = specialBorderWidth; outerStyle.width = outerWidth; break; case 'top': style.borderLeft = `${normalBorderWidth}px solid transparent`; style.borderRight = `${normalBorderWidth}px solid transparent`; style.borderBottomStyle = 'solid'; style.borderBottomWidth = specialBorderWidth; outerStyle.height = outerWidth; break; case 'right': style.borderTop = `${normalBorderWidth}px solid transparent`; style.borderBottom = `${normalBorderWidth}px solid transparent`; style.borderLeftStyle = 'solid'; style.borderLeftWidth = specialBorderWidth; outerStyle.width = outerWidth; break; case 'bottom': style.borderLeft = `${normalBorderWidth}px solid transparent`; style.borderRight = `${normalBorderWidth}px solid transparent`; style.borderTopStyle = 'solid'; style.borderTopWidth = specialBorderWidth; outerStyle.height = outerWidth; break; default: } switch (name) { case 'marginLeft': style.marginLeft = 0; break; case 'paddingLeft': style.marginLeft = -outerWidth; outerStyle.marginLeft = outerSpace; break; case 'marginTop': style.marginTop = 0; break; case 'paddingTop': style.marginTop = -outerWidth; outerStyle.marginTop = outerSpace; break; case 'marginRight': style.marginLeft = -outerWidth * 3; outerStyle.marginLeft = outerSpace; break; case 'paddingRight': style.marginLeft = -specialBorderWidth / 2; break; case 'marginBottom': style.marginTop = -outerWidth * 3; outerStyle.marginTop = outerSpace; break; case 'paddingBottom': style.marginTop = -specialBorderWidth / 2; break; default: } return ( <Styled.ButtonContainer style={outerStyle}> <Styled.ButtonTriangle draggable={false} onMouseDown={this.handleMouseDown.bind(this, name as any)} style={style} theme={{ position }} /> </Styled.ButtonContainer> ); }; private handleInputLeave = (name: typings.MarginPaddingField) => { if (this.currentHolding !== '') { return; } // eslint-disable-next-line react/no-string-refs const inputElement = ReactDOM.findDOMNode(this.refs[`${name}Input`]) as HTMLInputElement; if (inputElement) { inputElement.blur(); } }; private handleInputEnter = (name: typings.MarginPaddingField) => { if (this.currentHolding !== '') { return; } // eslint-disable-next-line react/no-string-refs const inputElement = ReactDOM.findDOMNode(this.refs[`${name}Input`]) as HTMLInputElement; if (inputElement) { inputElement.focus(); inputElement.select(); } }; }
the_stack
/// <reference types="node" /> export = ImageKit; declare global { namespace ImageKit { type TransformationPosition = 'path' | 'query'; /** * Type of files to include in result set. Accepts three values: * all - include all types of files in result set * image - only search in image type files * non-image - only search in files which are not image, e.g., JS or CSS or video files. * * @see {@link https://docs.imagekit.io/api-reference/media-api/list-and-search-files} */ type FileType = 'all' | 'image' | 'non-image'; /** * Type of returned item. It can be either file or folder. */ type Item = 'file' | 'folder'; /** * @see {@link https://help.imagekit.io/en/articles/2434102-image-format-support-in-imagekit-for-resizing-compression-and-static-file-delivery} */ type FileFormat = | 'jpg' | 'png' | 'gif' | 'svg' | 'webp' | 'pdf' | 'js' | 'css' | 'txt' | 'mp4' | 'webm' | 'mov' | 'swf' | 'ts' | 'm3u8' | string; /** * @see {@link https://docs.imagekit.io/features/image-transformations} */ interface Transformation { /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#width-w} */ height?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#height-h} */ width?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#aspect-ratio-ar} */ aspectRatio?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#quality-q} */ quality?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#crop-crop-modes-and-focus} */ crop?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#crop-crop-modes-and-focus} */ cropMode?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#focus-fo} */ focus?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#examples-focus-using-cropped-image-coordinates} */ x?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#examples-focus-using-cropped-image-coordinates} */ y?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#format-f} */ format?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#radius-r} */ radius?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#background-color-bg} */ background?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#border-b} */ border?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#rotate-rt} */ rotation?: number | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#blur-bl} */ blur?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#named-transformation-n} */ named?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-image-oi} */ overlayImage?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-x-position-ox} */ overlayX?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-y-position-oy} */ overlayY?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-focus-ofo} */ overlayFocus?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-height-oh} */ overlayHeight?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-width-ow} */ overlayWidth?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-text-ot} */ overlayText?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-text-size-ots} */ overlayTextFontSize?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-text-color-otc} */ overlayTextColor?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-transparency-oa} */ overlayAlpha?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-text-typography-ott} */ overlayTextTypography?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#overlay-background-obg} */ overlayBackground?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/overlay#trimming-of-the-overlay-image} */ overlayImageTrim?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#progressive-image-pr} */ progressive?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#lossless-webp-and-png-lo} */ lossless?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#trim-edges-t} */ trim?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#image-metadata-md} */ metadata?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#color-profile-cp} */ colorProfile?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#default-image-di} */ defaultImage?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#dpr-dpr} */ dpr?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#sharpen-e-sharpen} */ effectSharpen?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#unsharp-mask-e-usm} */ effectUSM?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation#contrast-stretch-e-contrast} */ effectContrast?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#grayscale-e-grayscale} */ effectGray?: string | undefined; /** * @see {@link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#original-image-orig} */ original?: string | undefined; } interface UrlOptionsBase { /** * An array of objects specifying the transformations to be applied in the URL. * The transformation name and the value should be specified as a key-value pair in each object. * @see {@link https://docs.imagekit.io/features/image-transformations/chained-transformations} */ transformation?: Transformation[] | undefined; /** * Default value is path that places the transformation string as a path parameter in the URL. * Can also be specified as query which adds the transformation string as the query parameter tr in the URL. * If you use src parameter to create the URL, then the transformation string is always added as a query parameter. */ transformationPosition?: TransformationPosition | undefined; /** * These are the other query parameters that you want to add to the final URL. * These can be any query parameters and not necessarily related to ImageKit. * Especially useful, if you want to add some versioning parameter to your URLs. */ queryParameters?: { [key: string]: string | number } | undefined; /** * The base URL to be appended before the path of the image. * If not specified, the URL Endpoint specified at the time of SDK initialization is used. */ urlEndpoint?: string | undefined; /** * Default is false. If set to true, the SDK generates a signed image URL adding the image signature to the image URL. * If you are creating URL using src parameter instead of path then do correct urlEndpoint for this to work. * Otherwise returned URL will have wrong signature. */ signed?: boolean | undefined; /** * Meant to be used along with the signed parameter to specify the time in seconds from now when the URL should expire. * If specified, the URL contains the expiry timestamp in the URL and the image signature is modified accordingly. */ expireSeconds?: number | undefined; } interface UrlOptionsSrc extends UrlOptionsBase { /** * Conditional. This is the complete URL of an image already mapped to ImageKit. * For example, https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg. * Either the path or src parameter need to be specified for URL generation. */ src: string; path?: never | undefined; } interface UrlOptionsPath extends UrlOptionsBase { /** * Conditional. This is the path at which the image exists. * For example, /path/to/image.jpg. Either the path or src parameter need to be specified for URL generation. */ path: string; src?: never | undefined; } /** * Options for generating an URL * * @see {@link https://github.com/imagekit-developer/imagekit-nodejs#url-generation} */ type UrlOptions = UrlOptionsSrc | UrlOptionsPath; /** * Options used when uploading a file * * @see {@link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload#request-structure-multipart-form-data} */ interface UploadOptions { /** * This field accepts three kinds of values: * - binary - You can send the content of the file as binary. This is used when a file is being uploaded from the browser. * - base64 - Base64 encoded string of file content. * - url - URL of the file from where to download the content before uploading. * Downloading file from URL might take longer, so it is recommended that you pass the binary or base64 content of the file. * Pass the full URL, for example - https://www.example.com/rest-of-the-image-path.jpg. */ file: string | Buffer; /** * The name with which the file has to be uploaded. * The file name can contain: * - Alphanumeric Characters: a-z , A-Z , 0-9 * - Special Characters: . _ and - * Any other character including space will be replaced by _ */ fileName: string; /** * Whether to use a unique filename for this file or not. * - Accepts true or false. * - If set true, ImageKit.io will add a unique suffix to the filename parameter to get a unique filename. * - If set false, then the image is uploaded with the provided filename parameter and any existing file with the same name is replaced. * Default value - true */ useUniqueFileName?: boolean | undefined; /** * Set the tags while uploading the file. * - Comma-separated value of tags in format tag1,tag2,tag3. For example - t-shirt,round-neck,men * - The maximum length of all characters should not exceed 500. * - % is not allowed. * - If this field is not specified and the file is overwritten then the tags will be removed. */ tags?: string | undefined; /** * The folder path (e.g. /images/folder/) in which the image has to be uploaded. If the folder(s) didn't exist before, a new folder(s) is created. * The folder name can contain: * - Alphanumeric Characters: a-z , A-Z , 0-9 * - Special Characters: / _ and - * - Using multiple / creates a nested folder. * Default value - / */ folder?: string | undefined; /** * Whether to mark the file as private or not. This is only relevant for image type files. * - Accepts true or false. * - If set true, the file is marked as private which restricts access to the original image URL and unnamed image transformations without signed URLs. * Without the signed URL, only named transformations work on private images * Default value - false */ isPrivateFile?: boolean | undefined; /** * Define an important area in the image. This is only relevant for image type files. * To be passed as a string with the x and y coordinates of the top-left corner, and width and height of the area of interest in format x,y,width,height. For example - 10,10,100,100 * Can be used with fo-customtransformation. * If this field is not specified and the file is overwritten, then customCoordinates will be removed. */ customCoordinates?: string | undefined; /** * Comma-separated values of the fields that you want ImageKit.io to return in response. * * For example, set the value of this field to tags,customCoordinates,isPrivateFile,metadata to get value of tags, customCoordinates, isPrivateFile , and metadata in the response. */ responseFields?: string | undefined; } /** * Response from uploading a file * * @see {@link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload#response-code-and-structure-json} */ interface UploadResponse { /** * Unique fileId. Store this fileld in your database, as this will be used to perform update action on this file. */ fileId: string; /** * The name of the uploaded file. */ name: string; /** * The URL of the file. */ url: string; /** * In case of an image, a small thumbnail URL. */ thumbnailUrl: string; /** * Height of the uploaded image file. Only applicable when file type is image. */ height: number; /** * Width of the uploaded image file. Only applicable when file type is image. */ width: number; /** * Size of the uploaded file in bytes. */ size: number; /** * Type of file. It can either be image or non-image. */ fileType: FileType; /** * The path of the file uploaded. It includes any folder that you specified while uploading. */ filePath: string; /** * Array of tags associated with the image. */ tags?: string[] | undefined; /** * Is the file marked as private. It can be either true or false. */ isPrivateFile: boolean; /** * Value of custom coordinates associated with the image in format x,y,width,height. */ customCoordinates: string | null; /** * The metadata of the upload file. Use responseFields property in request to get the metadata returned in response of upload API. */ metadata?: string | undefined; } /** * List and search files options * * @see {@link https://docs.imagekit.io/api-reference/media-api/list-and-search-files} */ interface ListFileOptions { /** * Folder path if you want to limit the search within a specific folder. For example, /sales-banner/ will only search in folder sales-banner. */ path?: string | undefined; /** * Type of files to include in result set. Accepts three values: * all - include all types of files in result set * image - only search in image type files * non-image - only search in files which are not image, e.g., JS or CSS or video files. */ fileType?: FileType | undefined; /** * Comma-separated list of tags. Files matching any of the tags are included in result response. If no tag is matched, the file is not included in result set. */ tags?: string | undefined; /** * Whether to include folders in search results or not. By default only files are searched. * Accepts true and false. If this is set to true then tags and fileType parameters are ignored. */ includeFolder?: boolean | undefined; /** * The name of the file or folder. */ name?: string | undefined; /** * The maximum number of results to return in response: * Minimum value - 1 * Maximum value - 1000 * Default value - 1000 */ limit?: number | undefined; /** * The number of results to skip before returning results. * Minimum value - 0 * Default value - 0 */ skip?: number | undefined; } /** * * List and search response * * @see {@link https://docs.imagekit.io/api-reference/media-api/list-and-search-files#response-structure-and-status-code-application-json} */ interface ListFileResponse { /** * The unique fileId of the uploaded file. */ fileId: string; /** * Type of item. It can be either file or folder. */ type: Item; /** * Name of the file or folder. */ name: string; /** * The date and time when the file was first uploaded. The format is `YYYY-MM-DDTHH:mm:ss.sssZ`. */ createdAt: string; /** * The relative path of the file. In the case of an image, you can use this * path to construct different transformations. */ filePath: string; /** * Array of tags associated with the image. If no tags are set, it will be null. */ tags: string[] | null; /** * Is the file marked as private. It can be either true or false. */ isPrivateFile: boolean; /** * Value of custom coordinates associated with the image in format x,y,width,height. If customCoordinates are not defined then it is null. */ customCoordinates: string | null; /** * A publicly accessible URL of the file. */ url: string; /** * In case of an image, a small thumbnail URL. */ thumbnail: string; /** * The type of file, it could be either image or non-image. */ fileType: FileType; } /** * * File details such as tags, customCoordinates, and isPrivate properties using get file detail API. * * @see {@link https://docs.imagekit.io/api-reference/media-api/get-file-details} * @see {@link https://docs.imagekit.io/api-reference/media-api/update-file-details#understanding-response} */ interface FileDetailsResponse { /** * The unique fileId of the uploaded file. */ fileId: string; /** * Type of item. It can be either file or folder. */ type: Item; /** * Name of the file or folder. */ name: string; /** * The relative path of the file. In case of image, you can use this * path to construct different transformations. */ filePath: string; /** * Array of tags associated with the image. If no tags are set, it will be null. */ tags: string[] | null; /** * Is the file marked as private. It can be either true or false. */ isPrivateFile: boolean; /** * Value of custom coordinates associated with the image in format x,y,width,height. * If customCoordinates are not defined then it is null. */ customCoordinates: string | null; /** * A publicly accessible URL of the file. */ url: string; /** * In case of an image, a small thumbnail URL. */ thumbnail: string; /** * The type of file, it could be either image or non-image. */ fileType: FileType; } /** * Response when getting image exif, pHash and other metadata for uploaded files in ImageKit.io media library using this API. * * @see {@link https://docs.imagekit.io/api-reference/metadata-api/get-image-metadata-for-uploaded-media-files} */ interface FileMetadataResponse { height: number; width: number; size: number; format: FileFormat; hasColorProfile: boolean; quality: number; density: number; hasTransparency: boolean; /** * @see {@link https://docs.imagekit.io/api-reference/metadata-api#perceptual-hash-phash} */ pHash: string; /** * @see {@link https://docs.imagekit.io/api-reference/metadata-api#exif} */ exif: { image: { Make: string; Model: string; Orientation: number; XResolution: number; YResolution: number; ResolutionUnit: number; Software: string; ModifyDate: string; YCbCrPositioning: number; ExifOffset: number; GPSInfo: number; }; thumbnail: { Compression: number; XResolution: number; YResolution: number; ResolutionUnit: number; ThumbnailOffset: number; ThumbnailLength: number; }; exif: { ExposureTime: number; FNumber: number; ExposureProgram: number; ISO: number; ExifVersion: string; DateTimeOriginal: string; CreateDate: string; ShutterSpeedValue: number; ApertureValue: number; ExposureCompensation: number; MeteringMode: number; Flash: number; FocalLength: number; SubSecTime: string; SubSecTimeOriginal: string; SubSecTimeDigitized: string; FlashpixVersion: string; ColorSpace: number; ExifImageWidth: number; ExifImageHeight: number; InteropOffset: number; FocalPlaneXResolution: number; FocalPlaneYResolution: number; FocalPlaneResolutionUnit: number; CustomRendered: number; ExposureMode: number; WhiteBalance: number; SceneCaptureType: number; }; gps: { GPSVersionID: number[]; }; interoperability: { InteropIndex: string; InteropVersion: string; }; makernote: { [key: string]: string }; }; } /** * Options when updating file details such as tags and customCoordinates attribute using update file detail API. * * @see {@link https://docs.imagekit.io/api-reference/media-api/update-file-details} */ interface FileDetailsOptions { /** * Array of tags associated with the file. */ tags?: string[] | undefined; /** * Define an important area in the image. * Example - 50,50,500,500 */ customCoordinates?: string | undefined; } /** * Response when deleting multiple files from the media library. * * @see {@link https://docs.imagekit.io/api-reference/media-api/delete-files-bulk} */ interface BulkDeleteFilesResponse { /** * List of file ids of successfully deleted files */ successfullyDeletedFileIds: string[]; } interface BulkDeleteFilesError extends Error { help: string; missingFileIds: string[]; } /** * Response when purging CDN and ImageKit.io internal cache * * @see {@link https://docs.imagekit.io/api-reference/media-api/purge-cache#response-structure-and-status-code} */ interface PurgeCacheResponse { /** * requestId can be used to fetch the status of submitted purge request. */ requestId: string; } /** * Response when getting the status of submitted purge request. * * @see {@link https://docs.imagekit.io/api-reference/media-api/purge-cache-status#understanding-response} */ interface PurgeCacheStatusResponse { /** * Pending - The request has been successfully submitted, and purging is in progress. * Complete - The purge request has been successfully completed. And now you should get a fresh object. * Check the Age header in response to confirm this. */ status: 'Pending' | 'Completed'; } interface Callback<T, E extends Error = Error> { (error?: E, response?: T): void; } } class ImageKit { constructor(options: { publicKey: string; privateKey: string; urlEndpoint: string; transformationPosition?: ImageKit.TransformationPosition | undefined; }); /** * You can add multiple origins in the same ImageKit.io account. * URL endpoints allow you to configure which origins are accessible through your account and set their preference order as well. * * @see {@link https://github.com/imagekit-developer/imagekit-nodejs#url-generation} * @see {@link https://docs.imagekit.io/integration/url-endpoints} * * @param urlOptions */ url(urlOptions: ImageKit.UrlOptions): string; /** * This API can list all the uploaded files in your ImageKit.io media library. * For searching and filtering, you can use query parameters as described below. * * @see {@link https://docs.imagekit.io/api-reference/media-api/list-and-search-files} * * @param listFilesOptions * @param callback */ listFiles( listFilesOptions: ImageKit.ListFileOptions, callback: ImageKit.Callback<ImageKit.ListFileResponse>, ): void; /** * This API can list all the uploaded files in your ImageKit.io media library. * For searching and filtering, you can use query parameters as described below. * * @see {@link https://docs.imagekit.io/api-reference/media-api/list-and-search-files} * * @param listFilesOptions */ listFiles(listFilesOptions: ImageKit.ListFileOptions): Promise<ImageKit.ListFileResponse>; /** * You can upload files to ImageKit.io media library from your server-side using private API key authentication. * * File size limit * The maximum upload file size is limited to 25MB. * * @see {@link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload} * * @param uploadOptions * @param callback */ upload(uploadOptions: ImageKit.UploadOptions, callback: ImageKit.Callback<ImageKit.UploadResponse>): void; /** * You can upload files to ImageKit.io media library from your server-side using private API key authentication. * * File size limit * The maximum upload file size is limited to 25MB. * * @see {@link https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload} * * @param uploadOptions */ upload(uploadOptions: ImageKit.UploadOptions): Promise<ImageKit.UploadResponse>; /** * Get the file details such as tags, customCoordinates, and isPrivate properties using get file detail API. * * @see {@link https://docs.imagekit.io/api-reference/media-api/get-file-details} * * @param fileId * @param callback */ getFileDetails(fileId: string, callback: ImageKit.Callback<ImageKit.FileDetailsResponse>): void; /** * Get the file details such as tags, customCoordinates, and isPrivate properties using get file detail API. * * @see {@link https://docs.imagekit.io/api-reference/media-api/get-file-details} * * @param fileId */ getFileDetails(fileId: string): Promise<ImageKit.FileDetailsResponse>; /** * Get image exif, pHash and other metadata for uploaded files in ImageKit.io media library using this API. * * @see {@link https://docs.imagekit.io/api-reference/metadata-api/get-image-metadata-for-uploaded-media-files} * * @param fileId The unique fileId of the uploaded file. fileId is returned in list files API and upload API. * @param callback */ getFileMetadata(fileId: string, callback: ImageKit.Callback<ImageKit.FileMetadataResponse>): void; /** * Get image exif, pHash and other metadata for uploaded files in ImageKit.io media library using this API. * * @see {@link https://docs.imagekit.io/api-reference/metadata-api/get-image-metadata-for-uploaded-media-files} * * @param fileId The unique fileId of the uploaded file. fileId is returned in list files API and upload API. */ getFileMetadata(fileId: string): Promise<ImageKit.FileMetadataResponse>; /** * Update file details such as tags and customCoordinates attribute using update file detail API. * * @see {@link https://docs.imagekit.io/api-reference/media-api/update-file-details} * * @param fileId The unique fileId of the uploaded file. fileId is returned in list files API and upload API. * @param optionsFileDetails * @param callback */ updateFileDetails( fileId: string, optionsFileDetails: ImageKit.FileDetailsOptions, callback: ImageKit.Callback<ImageKit.FileDetailsResponse>, ): void; /** * Update file details such as tags and customCoordinates attribute using update file detail API. * * @see {@link https://docs.imagekit.io/api-reference/media-api/update-file-details} * * @param fileId The unique fileId of the uploaded file. fileId is returned in list files API and upload API. * @param optionsFileDetails */ updateFileDetails( fileId: string, optionsFileDetails: ImageKit.FileDetailsOptions, ): Promise<ImageKit.FileDetailsResponse>; /** * You can programmatically delete uploaded files in media library using delete file API. * * @see {@link https://docs.imagekit.io/api-reference/media-api/delete-file} * * @param fileId The unique fileId of the uploaded file. fileId is returned in list files API and upload API * @param callback */ deleteFile(fileId: string, callback: ImageKit.Callback<void>): void; /** * You can programmatically delete uploaded files in media library using delete file API. * * @see {@link https://docs.imagekit.io/api-reference/media-api/delete-file} * * @param fileId The unique fileId of the uploaded file. fileId is returned in list files API and upload API */ deleteFile(fileId: string): Promise<void>; /** * Deletes multiple files from the media library. * * @see {@link https://docs.imagekit.io/api-reference/media-api/delete-files-bulk} * * @param fileIds Each value should be a unique fileId of the uploaded file. fileId is returned in list files API and upload API * @param callback */ bulkDeleteFiles( fileIds: string[], callback: ImageKit.Callback<ImageKit.BulkDeleteFilesResponse, ImageKit.BulkDeleteFilesError>, ): void; /** * Deletes multiple files from the media library. * * @see {@link https://docs.imagekit.io/api-reference/media-api/delete-files-bulk} * * @param fileIds Each value should be a unique fileId of the uploaded file. fileId is returned in list files API and upload API */ bulkDeleteFiles(fileIds: string[]): Promise<ImageKit.BulkDeleteFilesResponse>; /** * This will purge CDN and ImageKit.io internal cache. * * @see {@link https://docs.imagekit.io/api-reference/media-api/purge-cache} * * @param fullUrl The exact URL of the file to be purged. For example - https://ik.imageki.io/your_imagekit_id/rest-of-the-file-path.jpg * @param callback */ purgeCache(fullUrl: string, callback: ImageKit.Callback<ImageKit.PurgeCacheResponse>): void; /** * This will purge CDN and ImageKit.io internal cache. * * @see {@link https://docs.imagekit.io/api-reference/media-api/purge-cache} * * @param fullUrl The exact URL of the file to be purged. For example - https://ik.imageki.io/your_imagekit_id/rest-of-the-file-path.jpg */ purgeCache(fullUrl: string): Promise<ImageKit.PurgeCacheResponse>; /** * Get the status of submitted purge request. * * @see {@link https://docs.imagekit.io/api-reference/media-api/purge-cache-status} * * @param cacheRequestId The requestId returned in response of purge cache API. * @param callback */ getPurgeCacheStatus( cacheRequestId: string, callback: ImageKit.Callback<ImageKit.PurgeCacheStatusResponse>, ): void; /** * Get the status of submitted purge request. * * @see {@link https://docs.imagekit.io/api-reference/media-api/purge-cache-status} * * @param cacheRequestId The requestId returned in response of purge cache API. */ getPurgeCacheStatus(cacheRequestId: string): Promise<ImageKit.PurgeCacheStatusResponse>; /** * Authentication parameter generation * * @see {@link https://github.com/imagekit-developer/imagekit-nodejs#authentication-parameter-generation} * * @param token * @param expire */ getAuthenticationParameters( token?: string, expire?: number, ): { token: string; expire: number; signature: string }; /** * Perceptual Hash (pHash) * Distance between two pHash values can be calculated using utility function * * @see {@link https://docs.imagekit.io/api-reference/metadata-api#perceptual-hash-phash} * * @param hashA * @param hashB */ pHashDistance(hashA: string, hashB: string): number; } }
the_stack
module P { /** Returns a new "Deferred" value that may be resolved or rejected. */ export function defer<Value>(): Deferred<Value> { return new DeferredI<Value>(); } /** Converts a value to a resolved promise. */ export function resolve<Value>(v: Value): Promise<Value> { return defer<Value>().resolve(v).promise(); } /** Returns a rejected promise. */ export function reject<Value>(err: Rejection): Promise<Value> { return defer<Value>().reject(err).promise(); } /** http://en.wikipedia.org/wiki/Anamorphism Given a seed value, unfold calls the unspool function, waits for the returned promise to be resolved, and then calls it again if a next seed value was returned. All the values of all promise results are collected into the resulting promise which is resolved as soon the last generated element value is resolved. */ export function unfold<Seed, Element>( unspool: (current: Seed) => { promise: Promise<Element>; next?: Seed }, seed: Seed) : Promise<Element[]> { var d = defer<Element[]>(); var elements: Element[] = new Array<Element>(); unfoldCore<Seed, Element>(elements, d, unspool, seed) return d.promise(); } function unfoldCore<Seed, Element>( elements: Element[], deferred: Deferred<Element[]>, unspool: (current: Seed) => { promise: Promise<Element>; next?: Seed }, seed: Seed): void { var result = unspool(seed); if (!result) { deferred.resolve(elements); return; } // fastpath: don't waste stack space if promise resolves immediately. while (result.next && result.promise.status == P.Status.Resolved) { elements.push(result.promise.result); result = unspool(result.next); if (!result) { deferred.resolve(elements); return; } } result.promise .done(v => { elements.push(v); if (!result.next) deferred.resolve(elements); else unfoldCore<Seed, Element>(elements, deferred, unspool, result.next); } ) .fail(e => { deferred.reject(e); } ); } /** The status of a Promise. Initially a Promise is Unfulfilled and may change to Rejected or Resolved. Once a promise is either Rejected or Resolved, it can not change its status anymore. */ export enum Status { Unfulfilled, Rejected, Resolved } /** If a promise gets rejected, at least a message that indicates the error or reason for the rejection must be provided. */ export interface Rejection { message: string; } /** Both Promise<T> and Deferred<T> share these properties. */ export interface PromiseState<Value> { /// The current status of the promise. status: Status; /// If the promise got resolved, the result of the promise. result?: Value; /// If the promise got rejected, the rejection message. error?: Rejection; } /** A Promise<Value> supports basic composition and registration of handlers that are called when the promise is fulfilled. When multiple handlers are registered with done(), fail(), or always(), they are called in the same order. */ export interface Promise<Value> extends PromiseState<Value> { /** Returns a promise that represents a promise chain that consists of this promise and the promise that is returned by the function provided. The function receives the value of this promise as soon it is resolved. If this promise fails, the function is never called and the returned promise will also fail. */ then<T2>(f: (v: Value) => Promise<T2>): Promise<T2>; then<T2>(f: (v: Value) => T2): Promise<T2>; /// Add a handler that is called when the promise gets resolved. done(f: (v: Value) => void ): Promise<Value>; /// Add a handler that is called when the promise gets rejected. fail(f: (err: Rejection) => void ): Promise<Value>; /// Add a handler that is called when the promise gets fulfilled (either resolved or rejected). always(f: (v?: Value, err?: Rejection) => void ): Promise<Value>; } /** Deferred<Value> supports the explicit resolving and rejecting of the promise and the registration of fulfillment handlers. A Deferred<Value> should be only visible to the function that initially sets up an asynchronous process. Callers of that function should only see the Promise<Value> that is returned by promise(). */ export interface Deferred<Value> extends PromiseState<Value> { /// Returns the encapsulated promise of this deferred instance. /// The returned promise supports composition but removes the ability to resolve or reject /// the promise. promise(): Promise<Value>; /// Resolve the promise. resolve(result: Value): Deferred<Value>; /// Reject the promise. reject(err: Rejection): Deferred<Value>; done(f: (v: Value) => void ): Deferred<Value>; fail(f: (err: Rejection) => void ): Deferred<Value>; always(f: (v?: Value, err?: Rejection) => void ): Deferred<Value>; } /** Creates a promise that gets resolved when all the promises in the argument list get resolved. As soon one of the arguments gets rejected, the resulting promise gets rejected. If no promises were provided, the resulting promise is immediately resolved. */ export function when(...promises: Promise<any>[]): Promise<any[]> { var allDone = defer<any[]>(); if (!promises.length) { allDone.resolve([]); return allDone.promise(); } var resolved = 0; var results: any[] = []; promises.forEach((p, i) => { p .done(v => { results[i] = v; ++resolved; if (resolved === promises.length && allDone.status !== Status.Rejected) allDone.resolve(results); } ) .fail(e => { if (allDone.status !== Status.Rejected) allDone.reject(new Error("when: one or more promises were rejected")); } ); } ); return allDone.promise(); } /** Implementation of a promise. The Promise<Value> instance is a proxy to the Deferred<Value> instance. */ class PromiseI<Value> implements Promise<Value> { constructor(public deferred: DeferredI<Value>) { } get status(): Status { return this.deferred.status; } get result(): Value { return this.deferred.result; } get error(): Rejection { return this.deferred.error; } done(f: (v: Value) => void ): Promise<Value> { this.deferred.done(f); return this; } fail(f: (err: Rejection) => void ): Promise<Value> { this.deferred.fail(f); return this; } always(f: (v?: Value, err?: Rejection) => void ): Promise<Value> { this.deferred.always(f); return this; } then<T2>(f: (v: Value) => any): Promise<T2> { return this.deferred.then<any>(f); } } /** Implementation of a deferred. */ class DeferredI<Value> implements Deferred<Value>{ private _resolved: (v: Value) => void = _ => { }; private _rejected: (err: Rejection) => void = _ => { }; private _status: Status = Status.Unfulfilled; private _result: Value; private _error: Rejection = { message: "" }; private _promise: Promise<Value>; constructor() { this._promise = new PromiseI<Value>(this); } promise(): Promise<Value> { return this._promise; } get status(): Status { return this._status; } get result(): Value { if (this._status != Status.Resolved) throw new Error("Promise: result not available"); return this._result; } get error(): Rejection { if (this._status != Status.Rejected) throw new Error("Promise: rejection reason not available"); return this._error; } then<Result>(f: (v: Value) => any): Promise<Result> { var d = defer<Result>(); this .done(v => { var promiseOrValue = f(v); // todo: need to find another way to check if r is really of interface // type Promise<any>, otherwise we would not support other // implementations here. if (promiseOrValue instanceof PromiseI) { var p = <Promise<Result>> promiseOrValue; p.done(v2 => d.resolve(v2)) .fail(err => d.reject(err)); return p; } d.resolve(promiseOrValue); } ) .fail(err => d.reject(err)); return d.promise(); } done(f: (v: Value) => void ): Deferred<Value> { if (this.status === Status.Resolved) { f(this._result); return this; } if (this.status !== Status.Unfulfilled) return this; var prev = this._resolved; this._resolved = v => { prev(v); f(v); } return this; } fail(f: (err: Rejection) => void ): Deferred<Value> { if (this.status === Status.Rejected) { f(this._error); return this; } if (this.status !== Status.Unfulfilled) return this; var prev = this._rejected; this._rejected = e => { prev(e); f(e); } return this; } always(f: (v?: Value, err?: Rejection) => void ): Deferred<Value> { this .done(v => f(v)) .fail(err => f(null, err)); return this; } resolve(result: Value) { if (this._status !== Status.Unfulfilled) throw new Error("tried to resolve a fulfilled promise"); this._result = result; this._status = Status.Resolved; this._resolved(result); this.detach(); return this; } reject(err: Rejection) { if (this._status !== Status.Unfulfilled) throw new Error("tried to reject a fulfilled promise"); this._error = err; this._status = Status.Rejected; this._rejected(err); this.detach(); return this; } private detach() { this._resolved = _ => { }; this._rejected = _ => { }; } } /** Promise Generators and Iterators. */ export interface Generator<E> { (): Iterator<E>; } export interface Iterator<E> { advance(): Promise<boolean>; current: E; } export function generator<E>(g: () => () => Promise<E>): Generator<E> { return () => iterator<E>(g()); }; export function iterator<E>(f: () => Promise<E>): Iterator<E> { return new IteratorI<E>(f); } class IteratorI<E> implements Iterator<E> { current: E = undefined; constructor(private f: () => Promise<E>) { } advance() : Promise<boolean> { var res = this.f(); return res.then(value => { if (isUndefined(value)) return false; this.current = value; return true; } ); } } /** Iterator functions. */ export function each<E>(gen: Generator<E>, f: (e: E) => void ): Promise<{}> { var d = defer(); eachCore(d, gen(), f); return d.promise(); } function eachCore<E>(fin: Deferred<{}>, it: Iterator<E>, f: (e: E) => void ) : void { it.advance() .done(hasValue => { if (!hasValue) { fin.resolve({}); return; } f(it.current) eachCore<E>(fin, it, f); } ) .fail(err => fin.reject(err)); } /** std */ export function isUndefined(v: any) { return typeof v === 'undefined'; } }
the_stack
import { DefinitionNode, DirectiveDefinitionNode, DirectiveLocationEnum, DirectiveNode, DocumentNode, FieldDefinitionNode, GraphQLError, InputValueDefinitionNode, parse, SchemaDefinitionNode, Source, TypeNode, valueFromASTUntyped, ValueNode, NamedTypeNode, ArgumentNode, StringValueNode, ASTNode, SchemaExtensionNode, parseType } from "graphql"; import { Maybe } from "graphql/jsutils/Maybe"; import { BuiltIns, Schema, graphQLBuiltIns, newNamedType, NamedTypeKind, NamedType, SchemaDefinition, SchemaElement, ObjectType, InterfaceType, FieldDefinition, Type, ListType, OutputType, isOutputType, isInputType, InputType, NonNullType, ArgumentDefinition, InputFieldDefinition, DirectiveDefinition, UnionType, InputObjectType, EnumType, Extension } from "./definitions"; function buildValue(value?: ValueNode): any { // TODO: Should we rewrite a version of valueFromAST instead of using valueFromASTUntyped? Afaict, what we're missing out on is // 1) coercions, which concretely, means: // - for enums, we get strings // - for int, we don't get the validation that it should be a 32bit value. // - for ID, which accepts strings and int, we don't get int converted to string. // - for floats, we get either int or float, we don't get int converted to float. // - we don't get any custom coercion (but neither is buildSchema in graphQL-js anyway). // 2) type validation. return value ? valueFromASTUntyped(value) : undefined; } export function buildSchema(source: string | Source, builtIns: BuiltIns = graphQLBuiltIns, validate: boolean = true): Schema { return buildSchemaFromAST(parse(source), builtIns, validate); } export function buildSchemaFromAST(documentNode: DocumentNode, builtIns: BuiltIns = graphQLBuiltIns, validate: boolean = true): Schema { const schema = new Schema(builtIns); // We do a first pass to add all empty types and directives definition. This ensure any reference on one of // those can be resolved in the 2nd pass, regardless of the order of the definitions in the AST. const directiveDefinitionNodes = buildNamedTypeAndDirectivesShallow(documentNode, schema); // We then deal with directive definition first. This is mainly for the sake of core schemas: the core schema // handling in `Schema` detects that the schema is a core one when it see the application of `@core(feature: ".../core/...")` // to the schema element. But that detection necessitates that the corresponding directive definition has been fully // populated (and at this point, we don't really know the name of the `@core` directive since it can be renamed, so // we just handle all directives). for (const directiveDefinitionNode of directiveDefinitionNodes) { buildDirectiveDefinitionInner(directiveDefinitionNode, schema.directive(directiveDefinitionNode.name.value)!); } for (const definitionNode of documentNode.definitions) { switch (definitionNode.kind) { case 'OperationDefinition': case 'FragmentDefinition': throw new GraphQLError("Invalid executable definition found while building schema", definitionNode); case 'SchemaDefinition': buildSchemaDefinitionInner(definitionNode, schema.schemaDefinition); break; case 'SchemaExtension': buildSchemaDefinitionInner( definitionNode, schema.schemaDefinition, schema.schemaDefinition.newExtension()); break; case 'ScalarTypeDefinition': case 'ObjectTypeDefinition': case 'InterfaceTypeDefinition': case 'UnionTypeDefinition': case 'EnumTypeDefinition': case 'InputObjectTypeDefinition': buildNamedTypeInner(definitionNode, schema.type(definitionNode.name.value)!); break; case 'ScalarTypeExtension': case 'ObjectTypeExtension': case 'InterfaceTypeExtension': case 'UnionTypeExtension': case 'EnumTypeExtension': case 'InputObjectTypeExtension': const toExtend = schema.type(definitionNode.name.value)!; const extension = toExtend.newExtension(); extension.sourceAST = definitionNode; buildNamedTypeInner(definitionNode, toExtend, extension); break; } } Schema.prototype['forceSetCachedDocument'].call(schema, documentNode); if (validate) { schema.validate(); } return schema; } function buildNamedTypeAndDirectivesShallow(documentNode: DocumentNode, schema: Schema): DirectiveDefinitionNode[] { const directiveDefinitionNodes = []; for (const definitionNode of documentNode.definitions) { switch (definitionNode.kind) { case 'ScalarTypeDefinition': case 'ObjectTypeDefinition': case 'InterfaceTypeDefinition': case 'UnionTypeDefinition': case 'EnumTypeDefinition': case 'InputObjectTypeDefinition': case 'ScalarTypeExtension': case 'ObjectTypeExtension': case 'InterfaceTypeExtension': case 'UnionTypeExtension': case 'EnumTypeExtension': case 'InputObjectTypeExtension': // Note that because of extensions, this may be called multiple times for the same type. // But at the same time, we want to allow redefining built-in types, because some users do it. const existing = schema.type(definitionNode.name.value); if (!existing || existing.isBuiltIn) { schema.addType(newNamedType(withoutTrailingDefinition(definitionNode.kind), definitionNode.name.value)); } break; case 'DirectiveDefinition': directiveDefinitionNodes.push(definitionNode); schema.addDirectiveDefinition(definitionNode.name.value); break; } } return directiveDefinitionNodes; } type NodeWithDirectives = {directives?: ReadonlyArray<DirectiveNode>}; type NodeWithDescription = {description?: Maybe<StringValueNode>}; type NodeWithArguments = {arguments?: ReadonlyArray<ArgumentNode>}; function withoutTrailingDefinition(str: string): NamedTypeKind { const endString = str.endsWith('Definition') ? 'Definition' : 'Extension'; return str.slice(0, str.length - endString.length) as NamedTypeKind; } function getReferencedType(node: NamedTypeNode, schema: Schema): NamedType { const type = schema.type(node.name.value); if (!type) { throw new GraphQLError(`Unknown type ${node.name.value}`, node); } return type; } function withNodeAttachedToError(operation: () => void, node: ASTNode) { try { operation(); } catch (e) { if (e instanceof GraphQLError) { const allNodes: ASTNode | ASTNode[] = e.nodes ? [node, ...e.nodes] : node; throw new GraphQLError( e.message, allNodes, e.source, e.positions, e.path, e, e.extensions ); } else { throw e; } } } function buildSchemaDefinitionInner( schemaNode: SchemaDefinitionNode | SchemaExtensionNode, schemaDefinition: SchemaDefinition, extension?: Extension<SchemaDefinition> ) { for (const opTypeNode of schemaNode.operationTypes ?? []) { withNodeAttachedToError( () => schemaDefinition.setRoot(opTypeNode.operation, opTypeNode.type.name.value).setOfExtension(extension), opTypeNode); } schemaDefinition.sourceAST = schemaNode; schemaDefinition.description = 'description' in schemaNode ? schemaNode.description?.value : undefined; buildAppliedDirectives(schemaNode, schemaDefinition, extension); } function buildAppliedDirectives( elementNode: NodeWithDirectives, element: SchemaElement<any, any>, extension?: Extension<any> ) { for (const directive of elementNode.directives ?? []) { withNodeAttachedToError(() => { const d = element.applyDirective(directive.name.value, buildArgs(directive)); d.setOfExtension(extension); d.sourceAST = directive; }, directive); } } function buildArgs(argumentsNode: NodeWithArguments): Record<string, any> { const args = Object.create(null); for (const argNode of argumentsNode.arguments ?? []) { args[argNode.name.value] = buildValue(argNode.value); } return args; } function buildNamedTypeInner( definitionNode: DefinitionNode & NodeWithDirectives & NodeWithDescription, type: NamedType, extension?: Extension<any> ) { switch (definitionNode.kind) { case 'ObjectTypeDefinition': case 'ObjectTypeExtension': case 'InterfaceTypeDefinition': case 'InterfaceTypeExtension': const fieldBasedType = type as ObjectType | InterfaceType; for (const fieldNode of definitionNode.fields ?? []) { const field = fieldBasedType.addField(fieldNode.name.value); field.setOfExtension(extension); buildFieldDefinitionInner(fieldNode, field); } for (const itfNode of definitionNode.interfaces ?? []) { withNodeAttachedToError( () => { const itfName = itfNode.name.value; if (fieldBasedType.implementsInterface(itfName)) { throw new GraphQLError(`Type ${type} can only implement ${itfName} once.`); } fieldBasedType.addImplementedInterface(itfName).setOfExtension(extension); }, itfNode); } break; case 'UnionTypeDefinition': case 'UnionTypeExtension': const unionType = type as UnionType; for (const namedType of definitionNode.types ?? []) { withNodeAttachedToError( () => { const name = namedType.name.value; if (unionType.hasTypeMember(name)) { throw new GraphQLError(`Union type ${unionType} can only include type ${name} once.`); } unionType.addType(name).setOfExtension(extension); }, namedType); } break; case 'EnumTypeDefinition': case 'EnumTypeExtension': const enumType = type as EnumType; for (const enumVal of definitionNode.values ?? []) { const v = enumType.addValue(enumVal.name.value); v.description = enumVal.description?.value; v.setOfExtension(extension); buildAppliedDirectives(enumVal, v); } break; case 'InputObjectTypeDefinition': case 'InputObjectTypeExtension': const inputObjectType = type as InputObjectType; for (const fieldNode of definitionNode.fields ?? []) { const field = inputObjectType.addField(fieldNode.name.value); field.setOfExtension(extension); buildInputFieldDefinitionInner(fieldNode, field); } break; } buildAppliedDirectives(definitionNode, type, extension); type.description = definitionNode.description?.value; type.sourceAST = definitionNode; } function buildFieldDefinitionInner(fieldNode: FieldDefinitionNode, field: FieldDefinition<any>) { const type = buildTypeReferenceFromAST(fieldNode.type, field.schema()); field.type = ensureOutputType(type, field.coordinate, fieldNode); for (const inputValueDef of fieldNode.arguments ?? []) { buildArgumentDefinitionInner(inputValueDef, field.addArgument(inputValueDef.name.value)); } buildAppliedDirectives(fieldNode, field); field.description = fieldNode.description?.value; field.sourceAST = fieldNode; } function ensureOutputType(type: Type, what: string, node: ASTNode): OutputType { if (isOutputType(type)) { return type; } else { throw new GraphQLError(`The type of ${what} must be Output Type but got: ${type}, a ${type.kind}.`, node); } } function ensureInputType(type: Type, what: string, node: ASTNode): InputType { if (isInputType(type)) { return type; } else { throw new GraphQLError(`The type of ${what} must be Input Type but got: ${type}, a ${type.kind}.`, node); } } export function builtTypeReference(encodedType: string, schema: Schema): Type { return buildTypeReferenceFromAST(parseType(encodedType), schema); } function buildTypeReferenceFromAST(typeNode: TypeNode, schema: Schema): Type { switch (typeNode.kind) { case 'ListType': return new ListType(buildTypeReferenceFromAST(typeNode.type, schema)); case 'NonNullType': const wrapped = buildTypeReferenceFromAST(typeNode.type, schema); if (wrapped.kind == 'NonNullType') { throw new GraphQLError(`Cannot apply the non-null operator (!) twice to the same type`, typeNode); } return new NonNullType(wrapped); default: return getReferencedType(typeNode, schema); } } function buildArgumentDefinitionInner(inputNode: InputValueDefinitionNode, arg: ArgumentDefinition<any>) { const type = buildTypeReferenceFromAST(inputNode.type, arg.schema()); arg.type = ensureInputType(type, arg.coordinate, inputNode); arg.defaultValue = buildValue(inputNode.defaultValue); buildAppliedDirectives(inputNode, arg); arg.description = inputNode.description?.value; arg.sourceAST = inputNode; } function buildInputFieldDefinitionInner(fieldNode: InputValueDefinitionNode, field: InputFieldDefinition) { const type = buildTypeReferenceFromAST(fieldNode.type, field.schema()); field.type = ensureInputType(type, field.coordinate, fieldNode); field.defaultValue = buildValue(fieldNode.defaultValue); buildAppliedDirectives(fieldNode, field); field.description = fieldNode.description?.value; field.sourceAST = fieldNode; } function buildDirectiveDefinitionInner(directiveNode: DirectiveDefinitionNode, directive: DirectiveDefinition) { for (const inputValueDef of directiveNode.arguments ?? []) { buildArgumentDefinitionInner(inputValueDef, directive.addArgument(inputValueDef.name.value)); } directive.repeatable = directiveNode.repeatable; const locations = directiveNode.locations.map(({ value }) => value as DirectiveLocationEnum); directive.addLocations(...locations); directive.description = directiveNode.description?.value; directive.sourceAST = directiveNode; }
the_stack
import invariant from "invariant"; import { NotEnoughBalance, NotEnoughBalanceInParentAccount, InvalidAddressBecauseDestinationIsAlsoSource, RecommendUndelegation, NotSupportedLegacyAddress, } from "@ledgerhq/errors"; import { BigNumber } from "bignumber.js"; import { fromTransactionRaw } from "./transaction"; import type { DatasetTest } from "../../types"; import type { Transaction } from "./types"; import tezosScanAccounts1 from "./datasets/tezos.scanAccounts.1"; export const accountTZrevealedDelegating = makeAccount( "TZrevealedDelegating", "02389ffd73423626894cb151416e51c72ec285376673daf83545eb5edb45b261ce", "tezbox" ); const accountTZwithKT = makeAccount( "TZwithKT", "0294e8344ae6df2d3123fa100b5abd40cee339c67838b1c34c4f243cc582f4d2d8", "tezbox" ); const accountTZnew = makeAccount( "TZnew", "02a9ae8b0ff5f9a43565793ad78e10db6f12177d904d208ada591b8a5b9999e3fd", "tezbox" ); const accountTZnotRevealed = makeAccount( "TZnotRevealed", "020162dc75ad3c2b6e097d15a1513033c60d8a033f2312ff5a6ead812228d9d653", "tezosbip44h" ); const accountTZRevealedNoDelegate = makeAccount( "TZRevealedNoDelegate", "029bfe70b3e94ff23623f6c42f6e081a9ca8cc78f74b0d8da58f0d4cdc41c33c1a", "tezosbip44h" ); const accountTZemptyWithKT = makeAccount( "TZemptyWithKT", "020c38103f932f446dc4c09ac946e9643386609453e77716d3df45f1149aa52072", "tezbox" ); const addressAccountTZrevealedDelegating = "tz1boBHAVpwcvKkNFAQHYr7mjxAz1PpVgKq7"; const addressTZregular = "tz1T72nyqnJWwxad6RQnh7imKQz7mzToamWd"; const addressTZnew = "tz1VSichevvJSNkSSntgwKDKikWNB6iqNJii"; const addressKT = "KT1V99vDN5DHNpU9swVXg1cAT2ji981cccXC"; const addressDelegator = "tz1WCd2jm4uSt4vntk4vSuUWoZQGhLcDuR9q"; const reservedAmountForStorageLimit = (storageLimit) => new BigNumber(storageLimit || 0).times("1000"); const dataset: DatasetTest<Transaction> = { implementations: ["libcore"], // @ts-expect-error we disable the test by giving an empty object currencies: {} || { tezos: { FIXME_ignoreOperationFields: ["blockHeight"], scanAccounts: [tezosScanAccounts1], accounts: [ { FIXME_tests: [ "balance is sum of ops", // https://ledgerhq.atlassian.net/browse/LLC-591 ], raw: accountTZrevealedDelegating, transactions: [ { name: "send max to new account (explicit)", transaction: fromTransactionRaw({ amount: "0", recipient: addressTZnew, useAllAmount: true, family: "tezos", mode: "send", networkInfo: { family: "tezos", fees: "3075", }, fees: "3075", gasLimit: "10600", storageLimit: "300", taquitoError: null, }), expectedStatus: (account) => ({ errors: {}, warnings: { amount: new RecommendUndelegation(), }, estimatedFees: new BigNumber("3075"), amount: account.balance .minus(reservedAmountForStorageLimit("300")) .minus("3075"), totalSpent: account.balance, }), }, { name: "overflow send to new account", transaction: (t, account) => ({ ...t, amount: account.balance.minus(t.fees || 0).minus("1000"), recipient: addressTZnew, }), expectedStatus: { errors: { amount: new NotEnoughBalance(), }, warnings: {}, }, }, { name: "send max to new account (dynamic)", transaction: (t) => ({ ...t, recipient: addressTZnew, useAllAmount: true, }), expectedStatus: (account, { storageLimit, fees }) => ( invariant(fees, "fees are required"), { errors: {}, warnings: { amount: new RecommendUndelegation(), }, estimatedFees: fees, amount: account.balance .minus(reservedAmountForStorageLimit(storageLimit)) .minus(fees as BigNumber), totalSpent: account.balance, } ), }, { name: "send max to existing account", transaction: (t) => ({ ...t, recipient: addressTZregular, useAllAmount: true, }), expectedStatus: (account, { fees }) => ( invariant(fees, "fees are required"), { errors: {}, warnings: { amount: new RecommendUndelegation(), }, estimatedFees: fees, amount: account.balance.minus(fees as BigNumber), totalSpent: account.balance, } ), }, { name: "self tx forbidden", transaction: (t) => ({ ...t, recipient: addressAccountTZrevealedDelegating, amount: new BigNumber(0.1), }), expectedStatus: { errors: { recipient: new InvalidAddressBecauseDestinationIsAlsoSource(), }, warnings: {}, }, }, { name: "undelegate", transaction: (t) => ({ ...t, mode: "undelegate" }), expectedStatus: (account, { fees }) => ( invariant(fees, "fees are required"), { errors: {}, warnings: {}, amount: new BigNumber(0), estimatedFees: fees, } ), }, ], }, { FIXME_tests: [ "balance is sum of ops", // https://ledgerhq.atlassian.net/browse/LLC-591 ], raw: accountTZRevealedNoDelegate, transactions: [ { name: "send max to new account", transaction: (t) => ({ ...t, recipient: addressTZnew, useAllAmount: true, }), expectedStatus: (account, { storageLimit, fees }) => ( invariant(fees, "fees are required"), { errors: {}, warnings: {}, estimatedFees: fees, amount: account.balance .minus(reservedAmountForStorageLimit(storageLimit)) .minus(fees as BigNumber), totalSpent: account.balance, } ), }, { name: "send max to existing account", transaction: (t) => ({ ...t, recipient: addressTZregular, useAllAmount: true, }), expectedStatus: (account, { fees }) => ( invariant(fees, "fees are required"), { errors: {}, warnings: {}, estimatedFees: fees, amount: account.balance.minus(fees as BigNumber), totalSpent: account.balance, } ), }, { name: "delegate", transaction: (t) => ({ ...t, recipient: addressDelegator, mode: "delegate", }), expectedStatus: (account, { fees }) => ( invariant(fees, "fees are required"), { errors: {}, warnings: {}, amount: new BigNumber(0), estimatedFees: fees, } ), }, ], }, { raw: accountTZnotRevealed, FIXME_tests: [ "balance is sum of ops", // https://ledgerhq.atlassian.net/browse/LLC-591 ], transactions: [ { name: "send 10% to KT", transaction: (t, account) => ({ ...t, recipient: addressKT, amount: account.balance.div(10), }), expectedStatus: { errors: { recipient: new NotSupportedLegacyAddress(), }, warnings: {}, }, }, { name: "send 10% to existing tz", transaction: (t, account) => ({ ...t, recipient: addressTZnew, amount: account.balance.div(10), }), expectedStatus: (account, { fees }) => ( invariant(fees, "fees are required"), { errors: {}, warnings: {}, estimatedFees: (fees as BigNumber).times(2), amount: account.balance.div(10), totalSpent: account.balance .div(10) .plus((fees as BigNumber).times(2)), } ), }, ], }, { raw: accountTZnew, test: (expect, account) => { expect(account.operations).toEqual([]); }, transactions: [ { name: "send 10% to existing tz", transaction: (t) => ({ ...t, recipient: addressTZregular, useAllAmount: true, }), expectedStatus: { errors: { amount: new NotEnoughBalance(), }, warnings: {}, }, }, ], }, { FIXME_tests: [ "balance is sum of ops", // https://ledgerhq.atlassian.net/browse/LLC-503 // because of prev bug we have bug on: "from KT 2, send max to existing account", ], raw: accountTZwithKT, transactions: [ { name: "from KT 1, send max to new account", transaction: (t, account) => ( invariant(account.subAccounts, "subAccounts"), { ...t, subAccountId: account.subAccounts?.[0].id, recipient: addressTZnew, useAllAmount: true, } ), expectedStatus: ({ subAccounts }, { storageLimit, fees }) => ( invariant(fees && subAccounts, "fees are required"), { errors: {}, warnings: {}, estimatedFees: fees, amount: subAccounts?.[0].balance.minus( reservedAmountForStorageLimit(storageLimit) ), totalSpent: subAccounts?.[0].balance, } ), }, { name: "from KT 2, send max to existing account", transaction: (t, account) => ( invariant( account.subAccounts && account.subAccounts[1], "subAccounts" ), { ...t, subAccountId: account.subAccounts?.[1].id, recipient: addressTZnew, useAllAmount: true, } ), expectedStatus: ({ subAccounts }, { fees, storageLimit }) => ( invariant( subAccounts && fees && storageLimit, "fees are required" ), { errors: {}, warnings: {}, estimatedFees: fees, amount: subAccounts?.[1].balance, totalSpent: subAccounts?.[1].balance, } ), }, ], }, { FIXME_tests: [ "balance is sum of ops", // https://ledgerhq.atlassian.net/browse/LLC-591 ], raw: accountTZemptyWithKT, transactions: [ { name: "from KT 1, send max", transaction: (t, account) => ( invariant(account.subAccounts, "subAccounts"), { ...t, subAccountId: account.subAccounts?.[0].id, recipient: addressTZregular, useAllAmount: true, } ), expectedStatus: { errors: { amount: new NotEnoughBalanceInParentAccount(), }, warnings: {}, }, }, { name: "from KT 1, send 10%", transaction: (t, account) => ( invariant(account.subAccounts, "subAccounts"), { ...t, subAccountId: account.subAccounts?.[0].id, amount: account.balance.div(10), recipient: addressTZregular, } ), expectedStatus: { errors: { amount: new NotEnoughBalanceInParentAccount(), }, warnings: {}, }, }, ], }, ], }, }, }; export default dataset; function makeAccount(name, pubKey, derivationMode) { return { id: `libcore:1:tezos:${pubKey}:${derivationMode}`, seedIdentifier: pubKey, name: "Tezos " + name, derivationMode, index: 0, freshAddress: "", freshAddressPath: "", freshAddresses: [], blockHeight: 0, operations: [], pendingOperations: [], currencyId: "tezos", unitMagnitude: 6, lastSyncDate: "", balance: "0", xpub: pubKey, subAccounts: [], }; }
the_stack
import * as Express from 'express'; import * as httpstatus from 'http-status'; // local dependencies import * as store from '../db/store'; import * as Types from '../db/db-types'; import * as limits from '../db/limits'; import * as objectstore from '../objectstore'; import * as errors from './errors'; import * as auth from './auth'; import * as extensions from '../scratchx/extensions'; import * as scratchtfjs from '../scratchx/scratchtfjs'; import * as models from '../scratchx/models'; import * as status from '../scratchx/status'; import * as keys from '../scratchx/keys'; import * as classifier from '../scratchx/classify'; import * as training from '../scratchx/training'; import * as conversation from '../training/conversation'; import * as visrec from '../training/visualrecognition'; import * as urls from './urls'; import * as headers from './headers'; import * as env from '../utils/env'; import loggerSetup from '../utils/logger'; const log = loggerSetup(); async function getScratchKeys(req: Express.Request, res: Express.Response) { const classid: string = req.params.classid; const userid: string = req.params.studentid; const projectid: string = req.params.projectid; try { const scratchKeys = await store.findScratchKeys(userid, projectid, classid); if (scratchKeys.length === 0) { const newKeyInfo = await keys.createKey(projectid); return res.set(headers.NO_CACHE).json([ newKeyInfo ]); } return res.set(headers.NO_CACHE).json(scratchKeys.map((key) => { return { id : key.id, model : key.classifierid, }; })); } catch (err) { log.error({ err }, 'Failed to get keys'); errors.unknownError(res, err); } } async function classifyWithScratchKey(req: Express.Request, res: Express.Response) { const apikey = req.params.scratchkey; try { if (!req.query.data) { log.warn({ agent : req.header('X-User-Agent'), key : apikey, func : 'classifyWithScratchKey', }, 'Missing data'); throw new Error('Missing data'); } const scratchKey = await store.getScratchKey(apikey); if (req.header('if-modified-since') && scratchKey.updated && scratchKey.updated.toISOString() === req.header('if-modified-since')) { return res.sendStatus(httpstatus.NOT_MODIFIED); } const classes = await classifier.classify(scratchKey, req.query.data); return res.set(headers.CACHE_10SECONDS).jsonp(classes); } catch (err) { if (err.message === 'Missing data') { return res.status(httpstatus.BAD_REQUEST).jsonp({ error : 'Missing data' }); } if (err.message === conversation.ERROR_MESSAGES.TEXT_TOO_LONG) { return res.status(httpstatus.BAD_REQUEST).jsonp({ error : err.message }); } if (err.message === 'Unexpected response when retrieving credentials for Scratch') { return res.status(httpstatus.NOT_FOUND).jsonp({ error : 'Scratch key not found' }); } if (err.statusCode === httpstatus.BAD_REQUEST) { return res.status(httpstatus.BAD_REQUEST).jsonp({ error : err.message }); } const safeDataDebug = typeof req.query.data === 'string' ? req.query.data.substr(0, 100) : typeof req.query.data; log.error({ err, data : safeDataDebug, agent : req.header('X-User-Agent') }, 'Classify error (get)'); return res.status(httpstatus.INTERNAL_SERVER_ERROR).jsonp(err); } } async function postClassifyWithScratchKey(req: Express.Request, res: Express.Response) { const apikey = req.params.scratchkey; try { if (!req.body.data) { log.warn({ agent : req.header('X-User-Agent'), key : apikey, func : 'postClassifyWithScratchKey', }, 'Missing data'); throw new Error('Missing data'); } const scratchKey = await store.getScratchKey(apikey); if (req.header('if-modified-since') && scratchKey.updated && scratchKey.updated.toISOString() === req.header('if-modified-since')) { return res.sendStatus(httpstatus.NOT_MODIFIED); } const classes = await classifier.classify(scratchKey, req.body.data); return res.json(classes); } catch (err) { if (err.message === 'Unexpected response when retrieving credentials for Scratch') { return res.status(httpstatus.NOT_FOUND).json({ error : 'Scratch key not found' }); } if (err.message === conversation.ERROR_MESSAGES.TEXT_TOO_LONG) { return res.status(httpstatus.BAD_REQUEST).json({ error : err.message }); } if (err.statusCode === httpstatus.BAD_REQUEST) { return res.status(httpstatus.BAD_REQUEST).json({ error : err.message }); } if (err.statusCode === httpstatus.FORBIDDEN || err.statusCode === httpstatus.UNAUTHORIZED) { return res.status(httpstatus.CONFLICT).json({ error : 'The Watson credentials being used by your class were rejected.' }); } const safeDataDebug = typeof req.body.data === 'string' ? req.body.data.substr(0, 100) : typeof req.body.data; if (err.message === 'Missing data' || err.message === 'Invalid image data provided. Remember, only jpg and png images are supported.') { log.warn({ agent : req.header('X-User-Agent'), displayedHelp : req.body.displayedhelp, data : safeDataDebug, }, 'Missing data in Scratch key classification'); return res.status(httpstatus.BAD_REQUEST).json({ error : err.message }); } log.error({ err, data : safeDataDebug, agent : req.header('X-User-Agent') }, 'Classify error (post)'); return res.status(httpstatus.INTERNAL_SERVER_ERROR).json(err); } } function getSoundTrainingItem(info: Types.SoundTraining): Promise<any> { const urlSegments = info.audiourl.split('/'); if (urlSegments.length < 10) { throw new Error('Unexpected audio url'); } const soundSpec = { classid : urlSegments[3], userid : urlSegments[5], projectid : urlSegments[7], objectid : urlSegments[9], }; return objectstore.getSound(soundSpec) .then((audiodata) => { const soundTraining: any = info as any; soundTraining.audiodata = audiodata.body; return soundTraining; }); } function getImageTrainingItem(scratchKey: Types.ScratchKey, info: Types.ImageTraining, proxy: boolean): any { let imageurl: string; if (info.isstored) { // if it's stored, provide a URL to download the image from the ML for Kids server imageurl = env.getSiteHostUrl() + '/api/scratch/' + scratchKey.id + '/images' + info.imageurl; } else if (proxy) { // only if requested, provide a URL that downloads non-stored images through ML for Kids as a proxy imageurl = env.getSiteHostUrl() + '/api/scratch/' + scratchKey.id + '/images/api' + '/classes/classid' + '/students/userid' + '/projects/' + scratchKey.projectid + '/images/' + info.id + '?proxy=true'; } else { // otherwise, provide the canonical source URL imageurl = info.imageurl; } return { id : info.id, imageurl, label : info.label, }; } async function getTrainingData(req: Express.Request, res: Express.Response) { const apikey = req.params.scratchkey; try { const scratchKey = await store.getScratchKey(apikey); if (scratchKey.type === 'sounds') { const trainingInfo = await store.getSoundTraining(scratchKey.projectid, { start : 0, limit : limits.getStoreLimits().soundTrainingItemsPerProject, }); const trainingData = await Promise.all(trainingInfo.map(getSoundTrainingItem)); res.set(headers.CACHE_2MINUTES); return res.json(trainingData); } else if (scratchKey.type === 'imgtfjs') { const trainingInfo = await store.getImageTraining(scratchKey.projectid, { start : 0, limit : limits.getStoreLimits().imageTrainingItemsPerProject, }); const proxy = req.query.proxy === 'true'; const trainingData = trainingInfo.map((item) => getImageTrainingItem(scratchKey, item, proxy)); res.set(headers.CACHE_2MINUTES); return res.json(trainingData); } else { return res.status(httpstatus.METHOD_NOT_ALLOWED) .json({ error : 'Method not allowed', }); } } catch (err) { if (err.message === 'Unexpected response when retrieving credentials for Scratch') { return res.status(httpstatus.NOT_FOUND).json({ error : 'Scratch key not found' }); } log.error({ err, agent : req.header('X-User-Agent') }, 'Fetch error'); return res.status(httpstatus.INTERNAL_SERVER_ERROR).jsonp(err); } } async function getImageTrainingDataItem(req: Express.Request, res: Express.Response) { const apikey = req.params.scratchkey; try { const scratchKey = await store.getScratchKey(apikey); const imageKey = { classid : req.params.classid, userid : req.params.studentid, projectid : req.params.projectid, objectid : req.params.imageid, }; if (scratchKey.projectid !== imageKey.projectid) { return errors.forbidden(res); } let imageData: Buffer; if (req.query.proxy === 'true') { const project = await store.getProject(imageKey.projectid); if (!project || project.type !== 'imgtfjs'){ return errors.forbidden(res); } imageData = await visrec.getTrainingItemData(project, imageKey.objectid); } else { const image = await objectstore.getImage(imageKey); // // set headers dynamically based on the image we've fetched // res.setHeader('Content-Type', image.filetype); if (image.modified) { res.setHeader('Last-Modified', image.modified); } if (image.etag) { res.setHeader('ETag', image.etag); } imageData = image.body; } // This is slow, so encourage browsers to aggressively // cache the images rather than repeatedly download them // (This is safe as we don't allow images to be modified, // so it's okay to treat them as immutable). res.set(headers.CACHE_1YEAR); res.send(imageData); } catch (err) { if (err.message === 'Unexpected response when retrieving credentials for Scratch') { return res.status(httpstatus.NOT_FOUND).json({ error : 'Scratch key not found' }); } if (err.message === 'The specified key does not exist.') { return res.status(httpstatus.NOT_FOUND).json({ error : 'File not found' }); } return res.status(httpstatus.INTERNAL_SERVER_ERROR).json({ error : err.message }); } } async function storeTrainingData(req: Express.Request, res: Express.Response) { const apikey = req.params.scratchkey; try { if (!req.body.data || !req.body.label) { log.warn({ agent : req.header('X-User-Agent'), key : apikey, func : 'postStoreTrainingData', }, 'Missing data'); throw new Error('Missing data'); } const scratchKey = await store.getScratchKey(apikey); const stored = await training.storeTrainingData(scratchKey, req.body.label, req.body.data); return res.set(headers.NO_CACHE).json(stored); } catch (err) { if (err.message === 'Missing data' || err.message === 'Invalid data' || err.message === 'Invalid label' || err.message === 'Number is too small' || err.message === 'Number is too big') { return res.status(httpstatus.BAD_REQUEST).json({ error : err.message }); } if (err.message === 'Project already has maximum allowed amount of training data') { return res.status(httpstatus.CONFLICT).json({ error : err.message }); } if (err.message === 'Unexpected response when retrieving credentials for Scratch') { return res.status(httpstatus.NOT_FOUND).json({ error : 'Scratch key not found' }); } log.error({ err, datatype : typeof(req.body.data), agent : req.header('X-User-Agent') }, 'Store error'); return res.status(httpstatus.INTERNAL_SERVER_ERROR).json(err); } } async function getExtension(req: Express.Request, res: Express.Response, version: 2 | 3) { const apikey = req.params.scratchkey; try { const scratchKey = await store.getScratchKey(apikey); const project = await store.getProject(scratchKey.projectid); if (!project) { return errors.notFound(res); } if (project.type === 'numbers') { project.fields = await store.getNumberProjectFields(project.userid, project.classid, project.id); } const extension = await extensions.getScratchxExtension(scratchKey, project, version); return res.set('Content-Type', 'application/javascript') .set(headers.NO_CACHE) .send(extension); } catch (err) { if (err.message === 'Unexpected response when retrieving credentials for Scratch') { return res.status(httpstatus.NOT_FOUND).json({ error : 'Scratch key not found' }); } log.error({ err }, 'Failed to generate extension'); errors.unknownError(res, err); } } function getScratchxExtension(req: Express.Request, res: Express.Response) { getExtension(req, res, 2); } function getScratch3Extension(req: Express.Request, res: Express.Response) { getExtension(req, res, 3); } function handleTfjsException(err: any, res: Express.Response) { log.error({ err }, 'TensorFlow.js request exception'); if (err.statusCode === httpstatus.NOT_FOUND) { return res.status(httpstatus.BAD_REQUEST) .json({ error : 'Model not found' }); } errors.unknownError(res, err); } function getTfjsExtension(req: Express.Request, res: Express.Response) { const scratchkey = req.params.scratchkey; return extensions.getScratchTfjsExtension(scratchkey) .then((extension) => { return res.set('Content-Type', 'application/javascript') .set(headers.CACHE_1YEAR) .send(extension); }) .catch((err) => { handleTfjsException(err, res); }); } function generateTfjsExtension(req: Express.Request, res: Express.Response) { return scratchtfjs.generateUrl(req.body) .then((resp) => { return res.status(httpstatus.OK) .set(headers.CACHE_1YEAR) .json({ url : resp }); }) .catch((err) => { handleTfjsException(err, res); }); } async function getScratchxStatus(req: Express.Request, res: Express.Response) { const apikey = req.params.scratchkey; try { const scratchKey = await store.getScratchKey(apikey); const scratchStatus = await status.getStatus(scratchKey); return res.set(headers.NO_CACHE).jsonp(scratchStatus); } catch (err) { if (err.message === 'Unexpected response when retrieving credentials for Scratch') { return res.status(httpstatus.NOT_FOUND).jsonp({ error : 'Scratch key not found' }); } log.error({ err, agent : req.header('X-User-Agent') }, 'Status error'); errors.unknownError(res, err); } } async function trainNewClassifier(req: Express.Request, res: Express.Response) { const apikey = req.params.scratchkey; try { const scratchKey = await store.getScratchKey(apikey); const classifierStatus = await models.trainModel(scratchKey); return res.set(headers.NO_CACHE).jsonp(classifierStatus); } catch (err) { if (err.message === 'Only text or numbers models can be trained using a Scratch key') { return res.status(httpstatus.NOT_IMPLEMENTED).json({ error : err.message }); } log.error({ err, agent : req.header('X-User-Agent') }, 'Train error'); errors.unknownError(res, err); } } export default function registerApis(app: Express.Application) { app.get(urls.SCRATCHKEYS, auth.authenticate, auth.checkValidUser, auth.verifyProjectAccess, getScratchKeys); app.get(urls.SCRATCHKEY_CLASSIFY, classifyWithScratchKey); app.post(urls.SCRATCHKEY_CLASSIFY, postClassifyWithScratchKey); app.post(urls.SCRATCHKEY_MODEL, trainNewClassifier); app.get(urls.SCRATCHKEY_TRAIN, getTrainingData); app.get(urls.SCRATCHKEY_IMAGE, getImageTrainingDataItem); app.post(urls.SCRATCHKEY_TRAIN, storeTrainingData); app.post(urls.SCRATCHTFJS_EXTENSIONS, generateTfjsExtension); app.get(urls.SCRATCHKEY_EXTENSION, getScratchxExtension); app.get(urls.SCRATCH3_EXTENSION, getScratch3Extension); app.get(urls.SCRATCHTFJS_EXTENSION, getTfjsExtension); app.get(urls.SCRATCHKEY_STATUS, getScratchxStatus); }
the_stack
import { Request, Response } from 'express' import { JsonController, Param, Body, Req, Res, Get, Post, Put, Delete, UseBefore } from 'routing-controllers' import _ from 'lodash' import moment from 'moment' import BaseController from '~/src/controller/api/base' import { cleanProjectConfig } from '~/src/controller/proxy/_utils' import LoginMiddleware from '~/src/middleware/login' import MPageRecord from '~/src/model/page/record' import MProject, { TypeProject } from '~/src/model/project' import Util from '~/src/library/utils/modules/util' import env from '~/src/config/env' import Knex from '~/src/library/mysql' interface TypeProjectItem extends TypeProject { id: number pagesTotal?: number departmentId?: number departmentName?: string } @JsonController() @UseBefore(LoginMiddleware) class ProjectController extends BaseController { //创建 @Post('/api/v2/hetu/project/create') async create(@Req() request: Request) { const userInfo = await this.asyncGetUserInfo(request) const actor_ucid = `${userInfo.id}` const actor_user_name = userInfo.name // 获取页面配置 let { project_code } = request.body // 组装数据, 自动过滤掉undefined的值 let insertProjectData: { [key: string]: string } = {} let dataKeyList = [`name`, `project_code`, `department`] for (let dataKey of dataKeyList) { if (_.has(request.body, dataKey)) { insertProjectData[dataKey] = request.body[dataKey] } } // 必传字段校验 const requiredFields = MProject.requiredFields for (let item of requiredFields) { if (_.isUndefined(insertProjectData[item])) { return this.showError(`${item}不能为空`) } } // 检查project_code是否存在 let project = await MProject.asyncGetByProjectCode(project_code) if (project.id) { return this.showError(`项目创建失败, 项目:${project_code}已存在`) } insertProjectData.layout = JSON.stringify({ type: 'blank', menu_data: [] }) // 创建项目 let projectId = await MProject.asyncCreate(insertProjectData, actor_ucid, actor_user_name) if (projectId === 0) { return this.showError('创建失败') } // 创建管理员 const insertId = await Knex.queryBuilder() .insert({ project_id: projectId, user_name: actor_user_name, user_id: actor_ucid, role: 'super', create_user_id: '', create_user_name: '系统', }) .into('project_user') if (!insertId) { return this.showError('创建失败') } return this.showResult({ projectId }, '创建成功') } // 修改项目 @Post('/api/v2/hetu/project/update') async update(@Req() request: Request) { const userInfo = await this.asyncGetUserInfo(request) const actor_ucid = `${userInfo.id}` // 获取页面配置 let { id: project_id, project_code } = request.body // 权限判断 const canUpdate = await MProject.hasPermission(actor_ucid, project_id) if (!canUpdate) { // 没有权限 return this.showError(`没有权限`) } // 必传字段校验 const requiredFields = [ 'id', 'project_code', 'name', 'layout_type', 'proxy_domin', 'proxy_code_key', 'proxy_success_code', 'proxy_message_key', 'proxy_data_key', 'whitelist', 'department', ] for (let item of requiredFields) { if (_.isUndefined(request.body[item])) { return this.showError(`${item}不能为空`) } } // 检查project_code是否存在 let project = await MProject.asyncGetByProjectCode(project_code) if (_.get(project, 'id') && project.id !== +project_id) { return this.showError(`更新失败, project_code:${project_code}已存在`) } let dataKeyList = [ `name`, `home`, 'proxy_domin', 'proxy_code_key', 'proxy_success_code', 'proxy_message_key', 'proxy_data_key', 'proxy_token_name', 'proxy_content_type', 'whitelist', 'department', 'logo', 'submodules', ] // 组装数据, 自动过滤掉undefined的值 let updateProjectData: { [key: string]: string } = {} for (let dataKey of dataKeyList) { if (_.has(request.body, dataKey)) { let _value = request.body[dataKey] switch (dataKey) { case 'logo': updateProjectData[dataKey] = _.isArray(_value) && _value[0] ? _value[0] : '' break default: updateProjectData[dataKey] = _value } } } const owner = request.body.owner if (!owner || !_.isPlainObject(owner)) { return this.showError('缺少参数owner') } if (owner.key) { updateProjectData.create_ucid = owner.key updateProjectData.create_user_name = owner.label.split(' ')[0] } else { return this.showError(`参数owner格式错误`) } let layout_menu_data = request.body.layout_menu_data if (_.isString(layout_menu_data)) { layout_menu_data = JSON.parse(layout_menu_data) } const layout = { type: request.body.layout_type, menu_data: layout_menu_data, } updateProjectData.layout = JSON.stringify(layout) let { is_api_sign, accessKeyId, accessKeySecret } = request.body updateProjectData.is_api_sign = is_api_sign if (is_api_sign) { updateProjectData.accessKeyId = accessKeyId updateProjectData.accessKeySecret = accessKeySecret } // 更新项目 let affectRowsCount = await MProject.asyncUpdate(project_id, updateProjectData) if (affectRowsCount === 0) { return this.showError('更新失败') } // 清空项目缓存 await cleanProjectConfig(project_code) return this.showResult(affectRowsCount, '更新成功') } // 获取用户有权限的项目列表 @Get('/api/v2/hetu/project/list') async list(@Req() request: Request, @Res() response: Response) { try { const userInfo = await this.asyncGetUserInfo(request) const ucid = `${userInfo.id}` const { pageSize = 1000, pageNum = 1, department, projectType } = request.query as any const isSuper = await MProject.hasSuperPermission(ucid) // 如果为超级管理员, 则返回全部项目 if (isSuper) { let results = await Knex('project_new') .innerJoin('department', 'project_new.department', 'department.id') .select( '*', 'project_new.id as id', 'project_new.name as name', 'project_new.department as departmentId', 'project_new.order as projectOrder', 'department.name as departmentName', 'department.order as departmentOrder', ) .orderBy([ { column: 'department.order', order: 'desc' }, { column: 'project_new.order', order: 'desc' }, ]) .limit(pageSize) .offset((pageNum - 1) * pageSize) results = results.map((v: any) => ({ ...v, role: 'super' })) const totalItem = await Knex.queryBuilder().select('*').from('project_new').count({ total: '*' }).first() const total = totalItem.total // 排序 return this.showResult({ total, list: results, }) } // 如果不是超级管理员 const results = await Knex('project_new') .innerJoin('department', 'project_new.department', 'department.id') .innerJoin('project_user', 'project_new.id', 'project_user.project_id') .select( 'project_new.*', 'project_new.order as projectOrder', 'department.order as departmentOrder', 'project_new.department as departmentId', 'department.name as departmentName', 'project_user.role as role', ) .andWhere('project_user.user_id', ucid) .orderBy([ { column: 'department.order', order: 'desc' }, { column: 'project_new.order', order: 'desc' }, ]) .limit(pageSize) .offset((pageNum - 1) * pageSize) const totalItem = await Knex('project_new') .innerJoin('project_user', 'project_new.id', 'project_user.project_id') .select('project_new.*') .andWhere('project_user.user_id', ucid) .count({ total: '*' }) .first() const total = totalItem.total return this.showResult({ list: results, total, }) } catch (e) { return this.showError(e.message || '服务器错误') } } // 获取某业务线的数据 @Get('/api/v3/hetu/project/list/department') async departmentDataV3(@Req() request: Request, @Res() response: Response) { try { let { department, rangePicker } = request.query as any if (department === undefined) { return this.showError(`缺少参数department`) } let _rangePicker if (rangePicker) { _rangePicker = rangePicker.split(',') if (_.isArray(_rangePicker)) { _rangePicker = _rangePicker.map((v) => moment(v).unix()) } } let { results: projects } = await MProject.asyncGetAllProjects({ department: +department, pageSize: 10000, pageNum: 1, minOrder: 9, }) // 项目总数 let pagesTotal = 0 // 范围内新增项目数 let newPagesTotal = 0 // 获取新增项目数 for (let i = 0; i < projects.length; i++) { let project = projects[i] const records = await Knex('page_record').where('project_id', project.id) if (_.isArray(records)) { // 当前项目的页面总数 project.pagesTotal = records.length pagesTotal += records.length if (_rangePicker) { project.isNew = project.create_at >= _rangePicker[0] // 计算新增页面数量 const newRecords = await Knex('page_record') .where('project_id', project.id) .whereBetween('create_at', _rangePicker) project.newPagesTotal = newRecords.length project.oldPagesTotal = project.pagesTotal - newRecords.length newPagesTotal += newRecords.length } } delete project.layout } // @ts-ignore let _results: any[] = projects.filter((v) => v.pagesTotal > 0).sort((a, b) => b.pagesTotal - a.pagesTotal) // 图表数据 let chartData = [] for (let i = 0; i < _results.length; i++) { // @ts-ignore _results[i].index = i + 1 chartData.push({ ..._results[i], _chart_type_: '新增页面', _chart_total_: _results[i].newPagesTotal, }) chartData.push({ ..._results[i], _chart_type_: '页面总数', _chart_total_: _results[i].pagesTotal, }) } return this.showResult({ total: _results.length, pagesTotal, newPagesTotal, list: _results, chartData, }) } catch (e) { return this.showError(e.message || '服务器错误') } } // 获取所有的项目列表 @Get('/api/v3/hetu/project/list/all') async allDataV3(@Req() request: Request, @Res() response: Response) { try { let {} = request.query let { results, total } = await MProject.asyncGetAllProjects({ pageSize: 10000, pageNum: 1, minOrder: 9 }) // 河图一期页面 164*2 个 const { total: totalPageCounts, projects } = await Util.getTotalPage(results) // @ts-ignore let _results = projects.sort((a, b) => b.pagesTotal - a.pagesTotal) interface DepartmentMap { [key: string]: { departmentId: number departmentName: string pagesTotal: number 页面总数: number projectTotal: number 项目总数: number projects: TypeProjectItem[] } } let departmentMap: DepartmentMap = {} _results.map((v) => { let { departmentId, departmentName, pagesTotal } = v if (departmentId === undefined || departmentName === undefined || pagesTotal === 0) return if (_.isPlainObject(departmentMap[`${departmentId}`])) { // 已存在 departmentMap[`${departmentId}`].projects.push(v) departmentMap[`${departmentId}`].projectTotal += 1 departmentMap[`${departmentId}`].项目总数 += 1 departmentMap[`${departmentId}`].pagesTotal += pagesTotal || 0 departmentMap[`${departmentId}`].页面总数 += pagesTotal || 0 } else { // 不存在 departmentMap[`${departmentId}`] = { departmentId, departmentName, projectTotal: 1, 项目总数: 1, pagesTotal: v.pagesTotal || 0, 页面总数: v.pagesTotal || 0, projects: [v], } } }) let list: any[] = [] Object.keys(departmentMap).map((v) => { list.push(departmentMap[v]) }) list = list.sort((a, b) => b.pagesTotal - a.pagesTotal).map((v, i) => ({ ...v, index: i + 1 })) return this.showResult({ total, totalPageCounts, list, }) } catch (e) { return this.showError(e.message || '服务器错误') } } // 获取所有的项目列表 @Get('/api/v4/hetu/project/list') async listAll4(@Req() request: Request, @Res() response: Response) { try { let { pageSize = 1000, pageNum = 1 } = request.query as any let offset = (pageNum - 1) * pageSize offset = offset < 0 ? 0 : offset let projects = await Knex('project_new').select('*').offset(offset).limit(pageSize) let item = await Knex('project_new').select('*').count({ total: '*' }) const total = _.get(item, [0, 'total'], 0) return this.showResult({ total, list: projects, }) } catch (e) { return this.showError(e.message || '服务器错误') } } // 删除项目 @Post('/api/v2/hetu/project/delete') async delete(@Req() request: Request, @Res() response: Response) { try { const userInfo = await this.asyncGetUserInfo(request) const actor_ucid = `${userInfo.id}` let { id: project_id } = request.body // 权限判断 const canDelete = await MProject.hasPermission(actor_ucid, project_id) if (!canDelete) { return this.showError('无权删除') } if (_.isUndefined(project_id)) { return this.showError('project_id为必填项') } let rawRecordList = await MPageRecord.asyncGetList(project_id, 1, 1000) let num = _.get(rawRecordList, 'length', 0) if (num > 0) { return this.showError('请先删除项目中的页面, 再删除项目') } const project = await MProject.asyncGetByProjectId(project_id) const projectCode = _.get(project, 'project_code') if (!projectCode) { return this.showError(`项目project_id=${project_id}不存在`) } const affectRowsCount = await MProject.asyncDelete(project_id) if (affectRowsCount === 0) { return this.showError('删除失败') } // 清空proxyHost缓存 cleanProjectConfig(projectCode) return this.showResult(affectRowsCount, '删除成功') } catch (e) { return this.showError(e.message) } } // 获取项目详情 @Get('/api/v2/hetu/project/detail') async get(@Req() request: Request, @Res() response: Response) { const userInfo = await this.asyncGetUserInfo(request) let currentUcid = `${userInfo.id}` let { id: project_id, path: page_path, checkRole } = request.query as any let project: any = {} if (page_path) { let pageId = await MPageRecord.asyncGetId(page_path) // 根据页面路径获取项目详情 if (pageId === 0) { // 如果页面不存在 return this.showError(`页面${page_path}对应的项目不存在`, {}, 404) } let page = await MPageRecord.asyncGet(pageId) project_id = page.project_id } if (!_.isUndefined(project_id)) { project = await MProject.asyncGetByProjectId(project_id) // 根据project_id获取项目详情 } if (!_.get(project, 'id')) { return this.showError(`项目不存在:project_id=${project_id}`) } // 是否拥有项目权限 const role = await MProject.getRole(currentUcid, project_id as number) if (checkRole && role !== 'super') { return this.showError('您无权访问该项目', {}, 403) } project.role = role project.env = Util.parseJSONWithDefault(project.env, {}) const layout = Util.parseJSONWithDefault(project.layout, {}) project.layout = layout for (let key in layout) { project[`layout_${key}`] = layout[key] } if (!project.proxy_domin) { // 如果domin不存在, 则从proxy_host里面获取 const proxy_host = Util.parseJSONWithDefault(project.proxy_host, {}) const _env = env === 'prod' ? env : 'test' project.proxy_domin = _.get(proxy_host, _env) } if (project.proxy_code_key === undefined) { project.proxy_code_key = 'status' } if (project.proxy_success_code === undefined) { project.proxy_success_code = 1 } if (project.proxy_message_key === undefined) { project.proxy_message_key = 'message' } if (project.proxy_content_type === undefined) { project.proxy_content_type = 'application/json' } if (project.proxy_token_name === undefined) { project.proxy_token_name = 'proxy_token_name' } project.owner = { label: `${project.create_user_name} ${project.create_ucid}`, key: project.create_ucid, } return this.showResult(project) } } export default ProjectController
the_stack
import { version as v } from "../package.json"; const version: string = v; type ErrCb = ( indexes: [from: number, to: number][], explanation: string, isFixable: boolean ) => void; interface Obj { [key: string]: any; } interface Opts { from: number; to: number; offset: number; leadingWhitespaceOK: boolean; trailingWhitespaceOK: boolean; oneSpaceAfterCommaOK: boolean; innerWhitespaceAllowed: boolean; separator: string; cb: null | ((from: number, to: number) => void); errCb: null | ErrCb; } function processCommaSep(str: string, originalOpts?: Partial<Opts>): void { console.log( `029 processCommaSep: INCOMING ${`\u001b[${33}m${`str`}\u001b[${39}m`}: ${JSON.stringify( str, null, 0 )}` ); console.log( `036 processCommaSep: INCOMING ${`\u001b[${33}m${`originalOpts`}\u001b[${39}m`} keys: ${JSON.stringify( originalOpts, null, 0 )}` ); // insurance: if (typeof str !== "string") { throw new Error( `string-process-comma-separated: [THROW_ID_01] input must be string! It was given as ${typeof str}, equal to:\n${JSON.stringify( str, null, 4 )}` ); } else if ( !str.length || !originalOpts || (!originalOpts.cb && !originalOpts.errCb) ) { // if input str is empty or there are no callbacks, exit early return; } // opts preparation: const defaults: Opts = { from: 0, to: str.length, offset: 0, leadingWhitespaceOK: false, trailingWhitespaceOK: false, oneSpaceAfterCommaOK: false, innerWhitespaceAllowed: false, separator: ",", cb: null, errCb: null, }; const opts: Opts = { ...defaults, ...originalOpts }; // patch from/to values, they might have been given as nulls etc. if (!Number.isInteger(originalOpts.from)) { opts.from = 0; } if (!Number.isInteger(originalOpts.to)) { opts.to = str.length; } if (!Number.isInteger(originalOpts.offset)) { opts.offset = 0; } console.log( `087 processCommaSep: FINAL ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify( opts, null, 4 )}; plus, ${typeof opts.cb} opts.cb; ${typeof opts.errCb} opts.errCb` ); // action: let chunkStartsAt: number | null = null; let whitespaceStartsAt: number | null = null; let firstNonwhitespaceNonseparatorCharFound = false; let separatorsArr = []; // needed to catch trailing separators let lastNonWhitespaceCharAt: number | null = null; let fixable = true; for (let i = opts.from as number; i < (opts.to as number); i++) { console.log( `${`\u001b[${36}m${`----------------------------------- str[${i}] = ${JSON.stringify( str[i], null, 0 )} -----------------------------------`}\u001b[${39}m`}` ); // catch the last nonwhitespace char if (str[i].trim() && str[i] !== opts.separator) { lastNonWhitespaceCharAt = i; console.log( `115 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`lastNonWhitespaceCharAt`}\u001b[${39}m`} = ${lastNonWhitespaceCharAt}` ); } // catch the beginning of a chunk if ( chunkStartsAt === null && str[i].trim() && (!opts.separator || str[i] !== opts.separator) ) { if (!firstNonwhitespaceNonseparatorCharFound) { firstNonwhitespaceNonseparatorCharFound = true; console.log( `128 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`firstNonwhitespaceNonseparatorCharFound`}\u001b[${39}m`} = ${firstNonwhitespaceNonseparatorCharFound}` ); } // if there was only one separator up to now, wipe it if (separatorsArr.length) { if (separatorsArr.length > 1) { // eslint-disable-next-line no-loop-func separatorsArr.forEach((separatorsIdx, orderNumber) => { if (orderNumber) { (opts as Obj).errCb( [ [ separatorsIdx + opts.offset, separatorsIdx + 1 + opts.offset, ], ], "Remove separator.", fixable ); } }); } separatorsArr = []; console.log( `153 ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} ${`\u001b[${33}m${`separatorsArr`}\u001b[${39}m`}` ); } chunkStartsAt = i; console.log( `159 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`chunkStartsAt`}\u001b[${39}m`} = ${chunkStartsAt}` ); } // catch the ending of a chunk if ( Number.isInteger(chunkStartsAt) && ((i > (chunkStartsAt as number) && opts.separator && str[i] === opts.separator) || i + 1 === opts.to) ) { console.log(`171 chunk ends`); const chunk = str.slice( chunkStartsAt as number, i + 1 === opts.to && str[i] !== opts.separator && str[i].trim() ? i + 1 : i ); console.log( `179 ${`\u001b[${32}m${`EXTRACTED`}\u001b[${39}m`} ${`\u001b[${33}m${`chunk`}\u001b[${39}m`} = "${`\u001b[${35}m${chunk}\u001b[${39}m`}"` ); // ping the cb if (typeof opts.cb === "function") { console.log( `185 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} ${JSON.stringify( [ (chunkStartsAt as number) + opts.offset, (i + 1 === opts.to && str[i] !== opts.separator && str[i].trim() ? i + 1 : (lastNonWhitespaceCharAt as number) + 1) + opts.offset, ], null, 4 )}` ); opts.cb( (chunkStartsAt as number) + opts.offset, (i + 1 === opts.to && str[i] !== opts.separator && str[i].trim() ? i + 1 : (lastNonWhitespaceCharAt as number) + 1) + opts.offset ); } // reset chunkStartsAt = null; console.log( `207 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`} ${`\u001b[${33}m${`chunkStartsAt`}\u001b[${39}m`} = ${chunkStartsAt}` ); } // catch the beginning of a whitespace if (!str[i].trim() && whitespaceStartsAt === null) { whitespaceStartsAt = i; console.log( `215 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`whitespaceStartsAt`}\u001b[${39}m`} = ${whitespaceStartsAt}` ); } // catch the ending of a whitespace if (whitespaceStartsAt !== null && (str[i].trim() || i + 1 === opts.to)) { console.log(`221 whitespace ends`); if (whitespaceStartsAt === opts.from) { console.log(`224 leading whitespace clauses`); if (!opts.leadingWhitespaceOK && typeof opts.errCb === "function") { console.log( `227 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} ${JSON.stringify( [ [ whitespaceStartsAt + opts.offset, (i + 1 === opts.to ? i + 1 : i) + opts.offset, ], "Remove whitespace.", ], null, 4 )}` ); opts.errCb( [ [ whitespaceStartsAt + opts.offset, (i + 1 === opts.to ? i + 1 : i) + opts.offset, ], ], "Remove whitespace.", fixable ); } // else - fine } else if (!str[i].trim() && i + 1 === opts.to) { // if it's trailing whitespace, we're on the last character // (right before opts.to) console.log(`254 trailing whitespace clauses`); if (!opts.trailingWhitespaceOK && typeof opts.errCb === "function") { console.log( `257 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} ${JSON.stringify( [[whitespaceStartsAt, i + 1], "Remove whitespace."], null, 4 )}` ); opts.errCb( [[whitespaceStartsAt + opts.offset, i + 1 + opts.offset]], "Remove whitespace.", fixable ); } // else - fine } else if ( (!opts.oneSpaceAfterCommaOK || !( str[i].trim() && i > (opts.from as number) + 1 && str[i - 1] === " " && str[i - 2] === "," )) && (!opts.innerWhitespaceAllowed || !( firstNonwhitespaceNonseparatorCharFound && str[whitespaceStartsAt - 1] && str[i].trim() && str[i] !== opts.separator && str[whitespaceStartsAt - 1] !== opts.separator )) ) { console.log( `288 ███████████████████████████████████████ regular whitespace clauses` ); // exclude single space after a comma, with condition that something // non-whitespacey follows // maybe opts.oneSpaceAfterCommaOK is on? let startingIdx = whitespaceStartsAt; let endingIdx = i; if (i + 1 === opts.to && str[i] !== opts.separator && !str[i].trim()) { endingIdx += 1; } // i + 1 === opts.to && str[i] !== opts.separator && str[i].trim() // ? i + 1 // : i; console.log( `304 ${`\u001b[${33}m${`endingIdx`}\u001b[${39}m`} = ${JSON.stringify( endingIdx, null, 4 )}` ); let whatToAdd = ""; if (opts.oneSpaceAfterCommaOK) { console.log(`opts.oneSpaceAfterCommaOK is on`); if ( str[whitespaceStartsAt] === " " && str[whitespaceStartsAt - 1] === opts.separator ) { // if first whitespace chunk's character is a space, leave it startingIdx += 1; } else if (str[whitespaceStartsAt] !== " ") { // if first whitespace chunk's character is not a space, // replace whole chunk with a space whatToAdd = " "; } } let message = "Remove whitespace."; // What if there's a space in the middle of a value, for example, URL? // <input accept="abc,def ghi,jkl"> // ^ // here. // We identify it by checking, is there a separator in front. console.log( `335 ██ str[whitespaceStartsAt - 1] = ${str[whitespaceStartsAt - 1]}` ); if ( !opts.innerWhitespaceAllowed && firstNonwhitespaceNonseparatorCharFound && str[whitespaceStartsAt - 1] && str[i].trim() && str[i] !== opts.separator && str[whitespaceStartsAt - 1] !== opts.separator ) { fixable = false; message = "Bad whitespace."; } console.log( `350 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} ${JSON.stringify( [ [[startingIdx + opts.offset, endingIdx + opts.offset, whatToAdd]], message, fixable, ], null, 4 )}` ); if (whatToAdd.length) { (opts as Obj).errCb( [[startingIdx + opts.offset, endingIdx + opts.offset, whatToAdd]], message, fixable ); } else { (opts as Obj).errCb( [[startingIdx + opts.offset, endingIdx + opts.offset]], message, fixable ); } // reset fixable fixable = true; } // reset whitespaceStartsAt = null; } // catch the separator if (str[i] === opts.separator) { console.log(`385 separator caught`); if (!firstNonwhitespaceNonseparatorCharFound) { console.log( `388 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} ${JSON.stringify( [i, i + 1, "Remove separator."], null, 4 )}` ); (opts as Obj).errCb( [[i + opts.offset, i + 1 + opts.offset]], "Remove separator.", fixable ); } else { separatorsArr.push(i); } } // | // | // | // | // | // | // | // | // | // BOTTOM RULES // | // | // | // | // | // | // | // | // | // catch the end of the string if (i + 1 === opts.to) { // eslint-disable-next-line no-loop-func separatorsArr.forEach((separatorsIdx) => { (opts as Obj).errCb( [[separatorsIdx + opts.offset, separatorsIdx + 1 + opts.offset]], "Remove separator.", fixable ); }); } // logging console.log(`${`\u001b[${90}m${`ENDING`}\u001b[${39}m`}`); console.log( `${`\u001b[${90}m${`separatorsArr = ${JSON.stringify( separatorsArr, null, 0 )}`}\u001b[${39}m`}` ); } } export { processCommaSep, version };
the_stack
import { maxBy, max } from "lodash-es"; import { strSimilarity } from "../util"; /**MOD上的裂罅属性 */ export interface RivenPropertyValue { id: string; name: string; value: number; } /** * 裂罅属性条目 * * 符号标记说明,如: DSR-Z 即为伤害多重射速负后座 */ export interface RivenProperty { id: string; name: string; eName: string; sName: string; prefix: string; subfix: string; onlyPositive?: boolean; onlyNegative?: boolean; nopercent?: boolean; negative?: boolean; noDmg?: boolean; displayPre?: string; eDisplayPre?: string; } const baseProperty: RivenProperty[] = [ { id: "0", sName: "暴击率", eName: "Critical Chance", name: "暴击率", prefix: "crita", subfix: "cron" }, // { id: "1", sName: "暴击伤害", eName: "Critical Damage", name: "暴击伤害", prefix: "acri", subfix: "tis" }, // { id: "2", sName: "触发率", eName: "Status Chance", name: "触发几率", prefix: "hexa", subfix: "dex", noDmg: true }, // { id: "3", sName: "触发时间", eName: "Status Duration", name: "触发时间", prefix: "deci", subfix: "des", noDmg: true }, // { id: "4", sName: "火伤", eName: "Heat", name: "火焰伤害", prefix: "igni", subfix: "pha", onlyPositive: true }, // { id: "5", sName: "冰伤", eName: "Cold", name: "冰冻伤害", prefix: "geli", subfix: "do", onlyPositive: true }, // { id: "6", sName: "毒伤", eName: "Toxin", name: "毒素伤害", prefix: "toxi", subfix: "tox", onlyPositive: true }, // { id: "7", sName: "电伤", eName: "Electricity", name: "电击伤害", prefix: "vexi", subfix: "tio", onlyPositive: true }, // { id: "8", sName: "冲击", eName: "Impact", name: "冲击伤害", prefix: "magna", subfix: "ton" }, // { id: "9", sName: "穿刺", eName: "Puncture", name: "穿刺伤害", prefix: "insi", subfix: "cak" }, // { id: "A", sName: "切割", eName: "Slash", name: "切割伤害", prefix: "sci", subfix: "sus" }, // { id: "G", sName: "Grineer伤害", eName: "Damage to Grineer", name: "对Grineer伤害", prefix: "argi", subfix: "con" }, // { id: "I", sName: "Infested伤害", eName: "Damage to Infested", name: "对Infested伤害", prefix: "pura", subfix: "ada" }, // { id: "C", sName: "Corpus伤害", eName: "Damage to Corpus", name: "对Corpus伤害", prefix: "manti", subfix: "tron" }, // ]; const base2Property: RivenProperty[] = baseProperty.map(v => v.id === "0" ? { id: "0", sName: "暴击率", eName: "Critical Chance", name: "暴击几率(重击时x2)", prefix: "crita", subfix: "cron" } : v ); const gunProperty: RivenProperty[] = [ { id: "D", sName: "伤害", eName: "Damage", name: "伤害", prefix: "visi", subfix: "ata" }, // { id: "S", sName: "多重", eName: "Multishot", name: "多重射击", prefix: "sati", subfix: "can" }, // { id: "R", sName: "射速", eName: "Fire Rate", name: "射速", prefix: "croni", subfix: "dra" }, // { id: "L", sName: "弹匣", eName: "Magazine Capacity", name: "弹匣容量", prefix: "arma", subfix: "tin" }, // { id: "F", sName: "装填", eName: "Reload Speed", name: "装填速度", prefix: "feva", subfix: "tak" }, // { id: "M", sName: "弹药", eName: "Ammo Maximum", name: "弹药最大值", prefix: "ampi", subfix: "bin", noDmg: true }, // { id: "P", sName: "穿透", eName: "Punch Through", name: "穿透", prefix: "lexi", subfix: "nok", onlyPositive: true, nopercent: true, noDmg: true }, // { id: "H", sName: "变焦", eName: "Zoom", name: "变焦", prefix: "hera", subfix: "lis", noDmg: true }, // { id: "V", sName: "弹道", eName: "Projectile Speed", name: "投射物速度", prefix: "conci", subfix: "nak", noDmg: true }, // { id: "Z", sName: "后坐", eName: "Weapon Recoil", name: "后坐力", prefix: "zeti", subfix: "mag", negative: true, noDmg: true }, // ]; const gun2Property: RivenProperty[] = gunProperty.map(v => v.id === "R" ? { id: "R", sName: "射速", eName: "Firerate (x2 for Bows)", name: "射速(弓类武器效果加倍)", prefix: v.prefix, subfix: v.subfix } : v ); const meleeProperty: RivenProperty[] = [ { id: "K", sName: "伤害", eName: "Melee Damage", name: "近战伤害", prefix: "visi", subfix: "ata" }, // { id: "T", sName: "范围", eName: "Range", name: "攻击范围", prefix: "locti", subfix: "tor", noDmg: true, nopercent: true }, // { id: "J", sName: "攻速", eName: "Attack Speed", name: "攻击速度", prefix: "croni", subfix: "dra" }, // { id: "B", sName: "初始连击", eName: "Initial Combo", name: "初始连击", prefix: "para", subfix: "um", noDmg: true, nopercent: true, onlyPositive: true }, // { id: "U", sName: "连击效率", eName: "Combo Efficiency", name: "连击效率", prefix: "forti", subfix: "us", noDmg: true }, // { id: "N", sName: "连击时间", eName: "Combo Duration", name: "连击持续时间", prefix: "tempi", subfix: "nem", nopercent: true, noDmg: true }, // { id: "E", sName: "滑行暴击", eName: "chance to be a Critical Hit.", eDisplayPre: "Slide Attack has", displayPre: "滑行攻击有", name: "的几率造成暴击", prefix: "pleci", subfix: "nent", }, // { id: "X", sName: "处决伤害", eName: "Finisher Damage", name: "处决伤害", prefix: "exi", subfix: "cta", noDmg: true }, // { id: "O", sName: "连击获取", eName: "Combo Count Chance", name: "的几率获得额外连击数", prefix: "laci", subfix: "nus", noDmg: true, onlyPositive: true }, // { id: "Q", sName: "连击获取", eName: "Combo Count Chance", name: "的几率无法获得连击数", prefix: "laci", subfix: "nus", noDmg: true, onlyNegative: true }, // ]; export interface RivenProperties { Rifle: RivenProperty[]; Shotgun: RivenProperty[]; Secondary: RivenProperty[]; Kitgun: RivenProperty[]; Melee: RivenProperty[]; Zaw: RivenProperty[]; "Arch-Gun": RivenProperty[]; "Arch-Melee": RivenProperty[]; Amp: RivenProperty[]; all: RivenProperty[]; } export type RivenTypes = keyof RivenProperties; export const RivenPropertyDataBase: RivenProperties = { Rifle: baseProperty.concat(gun2Property), Shotgun: baseProperty.concat(gun2Property.filter(v => v.id != "H")), Secondary: baseProperty.concat(gunProperty), Kitgun: baseProperty.concat(gunProperty), "Arch-Gun": baseProperty.concat(gun2Property), "Arch-Melee": [], Amp: [], Melee: base2Property.concat(meleeProperty), Zaw: base2Property.concat(meleeProperty), all: baseProperty.concat(gunProperty, meleeProperty), }; export const ExtraDmgSet = new Set(["4", "5", "6", "7", "8", "9", "A"]); const RPVBRifle = { 0: 15, // 暴击率 1: 12, // 暴击伤害 2: 9, // 触发几率 3: 10, // 触发时间 4: 9, // 火焰伤害 5: 9, // 冰冻伤害 6: 9, // 毒素伤害 7: 9, // 电击伤害 8: 12, // 冲击伤害 9: 12, // 穿刺伤害 A: 12, // 切割伤害 G: 4.5, // 对Grineer伤害 I: 4.5, // 对Infested伤害 C: 4.5, // 对Corpus伤害 D: 16.5, // 伤害 S: 9, // 多重射击 R: 6, // 射速(弓类武器效果加倍) L: 5, // 弹匣容量 F: 5, // 装填速度 M: 5, // 弹药最大值 P: 27, // 穿透 H: 6, // 变焦 V: 9, // 投射物速度 Z: -9, // 后坐力 }; const RPVBShotgun = { 0: 9, // 暴击率 1: 9, // 暴击伤害 2: 9, // 触发几率 3: 10, // 触发时间 4: 9, // 火焰伤害 5: 9, // 冰冻伤害 6: 9, // 毒素伤害 7: 9, // 电击伤害 8: 12, // 冲击伤害 9: 12, // 穿刺伤害 A: 12, // 切割伤害 G: 4.5, // 对Grineer伤害 I: 4.5, // 对Infested伤害 C: 4.5, // 对Corpus伤害 D: 16.5, // 伤害 S: 12, // 多重射击 R: 9, // 射速 L: 5, // 弹匣容量 F: 5, // 装填速度 M: 9, // 弹药最大值 P: 27, // 穿透 H: 6, // 变焦 V: 9, // 投射物速度 Z: -9, // 后坐力 }; const RPVBPistol = { 0: 15, // 暴击率 1: 9, // 暴击伤害 2: 9, // 触发几率 3: 10, // 触发时间 4: 9, // 火焰伤害 5: 9, // 冰冻伤害 6: 9, // 毒素伤害 7: 9, // 电击伤害 8: 12, // 冲击伤害 9: 12, // 穿刺伤害 A: 12, // 切割伤害 G: 4.5, // 对Grineer伤害 I: 4.5, // 对Infested伤害 C: 4.5, // 对Corpus伤害 D: 22, // 伤害 S: 12, // 多重射击 R: 7.5, // 射速 L: 5, // 弹匣容量 F: 5, // 装填速度 M: 9, // 弹药最大值 P: 27, // 穿透 H: 8, // 变焦 V: 9, // 投射物速度 Z: -9, // 后坐力 }; const RPVBArchgun = { 0: 10, // 暴击率 1: 8, // 暴击伤害 2: 6, // 触发几率 3: 10, // 触发时间 4: 12, // 火焰伤害 5: 12, // 冰冻伤害 6: 12, // 毒素伤害 7: 12, // 电击伤害 8: 9, // 冲击伤害 9: 9, // 穿刺伤害 A: 9, // 切割伤害 G: 4.5, // 对Grineer伤害 I: 4.5, // 对Infested伤害 C: 4.5, // 对Corpus伤害 D: 10, // 伤害 S: 6, // 多重射击 R: 6, // 射速 L: 6, // 弹匣容量 F: 10, // 装填速度 M: 9, // 弹药最大值 P: 27, // 穿透 H: 6, // 变焦 V: 9, // 投射物速度 Z: -9, // 后坐力 }; const RPVBMelee = { 0: 18, // 暴击率 1: 9, // 暴击伤害 2: 9, // 触发几率 3: 10, // 触发时间 4: 9, // 火焰伤害 5: 9, // 冰冻伤害 6: 9, // 毒素伤害 7: 9, // 电击伤害 8: 12, // 冲击伤害 9: 12, // 穿刺伤害 A: 12, // 切割伤害 G: 4.5, // 对Grineer伤害 I: 4.5, // 对Infested伤害 C: 4.5, // 对Corpus伤害 K: 16.5, // 近战伤害 T: 20, // 攻击范围 J: 5.5, // 攻击速度 B: 220, // 初始连击 U: 6, // 连击效率 O: 6, // 连击获取 Q: 12, // 连击获取 N: 81, // 连击持续时间 E: 15, // 滑行攻击造成暴击几率 X: 12, // 处决伤害 }; /** * 属性基础值 */ export const RivenPropertyValueBaseDataBase = { Rifle: RPVBRifle, Shotgun: RPVBShotgun, Secondary: RPVBPistol, Kitgun: RPVBPistol, Melee: RPVBMelee, Zaw: RPVBMelee, "Arch-Gun": RPVBArchgun, }; export const ModTypeTable = { Rifle: { name: "rifle", include: [0 /* MainTag.Rifle */] }, Shotgun: { name: "shotgun", include: [1 /* MainTag.Shotgun */] }, Secondary: { name: "secondary", include: [2, 3 /* MainTag.Secondary, MainTag.Kitgun */] }, Melee: { name: "melee", include: [4, 5 /* MainTag.Melee, MainTag.Zaw */] }, Archwing: { name: "archwing", include: [6, 7 /* MainTag["Arch-Gun"], MainTag["Arch-Melee"] */] }, }; const propRegExpsFactory = (name: RivenTypes) => new RegExp( `(?:(${RivenPropertyDataBase[name].map(v => v.prefix).join("|")})-)?(${RivenPropertyDataBase[name].map(v => v.prefix).join("|")})(${RivenPropertyDataBase[ name ] .map(v => v.subfix) .join("|")})`, "i" ); /** * 主要工具类 */ export class RivenDatabase { /** 属性名称 -> 属性 index */ private propDict = new Map<string, number>(); /** 武器名称 -> 倾向性 */ private ratioDict = new Map<string, number>(); private static instance = new RivenDatabase(); static PropRegExps = { Rifle: propRegExpsFactory("Rifle"), Shotgun: propRegExpsFactory("Shotgun"), Secondary: propRegExpsFactory("Secondary"), Kitgun: propRegExpsFactory("Kitgun"), Melee: propRegExpsFactory("Melee"), Zaw: propRegExpsFactory("Zaw"), "Arch-Gun": propRegExpsFactory("Arch-Gun"), "Arch-Melee": propRegExpsFactory("Arch-Melee"), }; static PrefixAll = new RegExp( `(?:${RivenPropertyDataBase.all.map(v => v.prefix).join("|")})(?:-|${RivenPropertyDataBase.all.map(v => v.subfix).join("|")})`, "i" ); reload() { RivenPropertyDataBase.all.forEach((v, i) => { this.propDict.set(v.id, i); this.propDict.set(v.eName, i); this.propDict.set(v.name, i); }); } static reload() { this.instance.reload(); } /** * 查询是否有这个属性 * @param name 属性名称 */ static hasProp(name: string) { return this.instance.propDict.has(name); } /** * 模糊识别属性名称 * @param prop 属性名称 */ static findMostSimProp(prop: string) { if (this.hasProp(prop)) return RivenPropertyDataBase.all[this.instance.propDict.get(prop)]; let propFinded = maxBy(RivenPropertyDataBase.all, v => max([strSimilarity(prop, v.eName), strSimilarity(prop, v.name)])); return propFinded; } /** * 通过名称或id获取属性 * @param nameOrId 属性名称|id */ static getPropByName(nameOrId: string) { return RivenPropertyDataBase.all[this.instance.propDict.get(nameOrId)]; } /** * 通过tag获取属性 * @param tag tag * @param stype * @param isPrefix 是否是前缀 */ static getPropByTag(tag: string, stype: string, isPrefix: boolean) { return RivenPropertyDataBase[stype].find(v => v[isPrefix ? "prefix" : "subfix"] == tag); } /** * 获取属性基础值 * @param weaponType 武器通用名称 * @param prop * @return 返回基础值 如果为-1说明错误 */ static getPropBaseValue(ratio: number, weaponType: string, propName: string): number { let prop = this.getPropByName(propName); if (weaponType in RivenPropertyValueBaseDataBase && prop) return RivenPropertyValueBaseDataBase[weaponType][prop.id] * ratio * (prop.nopercent ? 0.1 : 10); else return -1; } } (window as any).RivenDatabase = RivenDatabase;
the_stack
import { Conic } from './Conic'; import { Container } from '@pixi/display'; import { Point, Matrix, Transform } from '@pixi/math'; import { Renderer, Texture } from '@pixi/core'; import { ConicRenderer } from './ConicRenderer'; import mat3 from 'gl-mat3'; const tempMatrix = new Matrix(); /** * Draws a segment of conic section represented by the equation _k_<sup>2</sup>- _lm = 0_, where k, l, m are lines. * * This display-object shades the inside/outside of a conic section within a mesh. * * A conic curve can be represented in the form: _k_<sup>2</sup> - _lm = 0_, where k, l, m are lines described in * the form _ax + by + c = 0_. _l_ and _m_ are the tangents to the curve, and _k_ is a chord connecting the points * of tangency. */ export class ConicDisplay extends Container { public shape: Conic; public vertexData: Array<number>; public uvData: Array<number>; public indexData: Array<number>; protected _texture: Texture; protected _updateID: number; protected _transformID: number; protected _dirtyID: number; constructor(conic = new Conic(), texture: Texture) { super(); /** * The conic curve drawn by this graphic. */ this.shape = conic; /** * Flags whether the geometry data needs to be updated. */ this._dirtyID = 0; /** * The world transform ID last when the geometry was updated. */ this._transformID = 0; /** * Last {@link _dirtyID} when the geometry was updated. */ this._updateID = -1; /** * World positions of the vertices */ this.vertexData = []; /** * Texture positions of the vertices. */ this.uvData = []; this._texture = texture || Texture.WHITE; } /** * @see Conic#k */ get k(): [number, number, number] { return this.shape.k; } set k(line: [number, number, number]) { this.shape.setk(...line); } /** * @see Conic#l */ get l(): [number, number, number] { return this.shape.l; } set l(line: [number, number, number]) { this.shape.setl(...line); } /** * @see Conic#m */ get m(): [number, number, number] { return this.shape.m; } set m(line: [number, number, number]) { this.shape.setm(...line); } get texture(): Texture { return this._texture; } set texture(tex: Texture) { this._texture = tex || Texture.WHITE; } _calculateBounds(): void { this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length); } _render(renderer: Renderer): void { if (!renderer.plugins.conic) { renderer.plugins.conic = new ConicRenderer(renderer, null); } renderer.batch.setObjectRenderer(renderer.plugins.conic); renderer.plugins.conic.render(this); } /** * Draws the triangle formed by the control points of the shape. */ drawControlPoints(): this { const controlPoints = this.shape.controlPoints; this.drawTriangle( controlPoints[0].x, controlPoints[0].y, controlPoints[1].x, controlPoints[1].y, controlPoints[2].x, controlPoints[2].y, ); return this; } /** * Draw a triangle defined in texture space transformed into local space. Generally, you would want to draw the triangle * formed by the shape's control points. * * @param x0 * @param y0 * @param x1 * @param y1 * @param x2 * @param y2 */ drawTriangle(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number): this { const data = this.uvData; const i = data.length; data.length += 6; data[i] = x0; data[i + 1] = y0; data[i + 2] = x1; data[i + 3] = y1; data[i + 4] = x2; data[i + 5] = y2; return this; } /** * @param x * @param y * @param width * @param height */ drawRect(x: number, y: number, width: number, height: number): this { const data = this.uvData; const i = data.length; data.length += 12; data[i] = x; data[i + 1] = y; data[i + 2] = x + width; data[i + 3] = y; data[i + 4] = x + width; data[i + 5] = y + height; data[i + 6] = x; data[i + 7] = y; data[i + 8] = x + width; data[i + 9] = y + height; data[i + 10] = x; data[i + 11] = y + height; return this; } /** * Updates the geometry data for this conic. */ updateConic(): void { const vertexData = this.vertexData; const uvData = this.uvData; vertexData.length = uvData.length; const matrix = tempMatrix.copyFrom(this.worldTransform); const { a, b, c, d, tx, ty } = matrix; for (let i = 0, j = vertexData.length / 2; i < j; i++) { const x = uvData[(i * 2)]; const y = uvData[(i * 2) + 1]; vertexData[(i * 2)] = (a * x) + (c * y) + tx; vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty; } this._updateID = this._dirtyID; const indexData = this.indexData = new Array(vertexData.length / 2); // TODO: Remove indexData, pixi-batch-renderer might have a problem with it for (let i = 0, j = indexData.length; i < j; i++) { indexData[i] = i; } } /** * Sets the local-space control points of the curve. * @param c0 * @param c1 * @param c2 */ setControlPoints(c0: Point, c1: Point, c2: Point): void { const texturePoints = this.shape.controlPoints; this.setTransform(texturePoints[0], texturePoints[1], texturePoints[2], c0, c1, c2); } /** * Set the transform of the conic * * @param matrix - transformation between design space and texture space */ setTransform(matrix: Matrix): this; /** * Set the transformation by defining a triangle in design space _(a0, b0, c0)_ mapping to * the triangle _(a1, b1, c1)_ in texture space. * * @param a0 * @param b0 * @param c0 * @param a1 * @param b1 * @param c1 */ setTransform(a0: Point, b0: Point, c0: Point, a1: Point, b1: Point, c1: Point): this; /** * Set the transformation by defining the triangle in design space _(ax0, ay0), (bx0, by0), (cx0, cy0)_ * mapping to the triangle _(ax1, ay1), (bx1, by1), (cx1, cy1)_ in texture space. * * @param ax0 * @param ay0 * @param bx0 * @param by0 * @param cx0 * @param cy0 * @param ax1 * @param ay1 * @param bx1 * @param by1 * @param cx1 * @param cy1 */ setTransform(ax0: number, ay0: number, bx0: number, by0: number, cx0: number, cy0: number, ax1: number, ay1: number, bx1: number, by1: number, cx1: number, cy1: number): this; setTransform(...args: any): this { const transform = this.transform; const localTransform = transform.localTransform; transform._localID++; if (args.length === 1) { localTransform.copyFrom(args[0]); return this; } if (args.length === 9) { super.setTransform(...args); } localTransform.identity(); // Design space let ax0: number; let ay0: number; let bx0: number; let by0: number; let cx0: number; let cy0: number; // Texture space let ax1: number; let ay1: number; let bx1: number; let by1: number; let cx1: number; let cy1: number; if (args.length === 6) { const points = args as Point[]; ax0 = points[0].x; ay0 = points[0].y; bx0 = points[1].x; by0 = points[1].y; cx0 = points[2].x; cy0 = points[2].y; ax1 = points[3].x; ay1 = points[3].y; bx1 = points[4].x; by1 = points[4].y; cx1 = points[5].x; cy1 = points[5].y; } else { const coords = args as number[]; ax0 = coords[0]; ay0 = coords[1]; bx0 = coords[2]; by0 = coords[3]; cx0 = coords[4]; cy0 = coords[5]; ax1 = coords[6]; ay1 = coords[7]; bx1 = coords[8]; by1 = coords[9]; cx1 = coords[10]; cy1 = coords[11]; } const input = [ ax0, bx0, cx0, ay0, by0, cy0, 1, 1, 1, ]; const inverse = mat3.invert(input, input); // input * textureTransform = output // textureTransform = inverse(input) * output localTransform.a = (inverse[0] * ax1) + (inverse[3] * bx1) + (inverse[6] * cx1); localTransform.c = (inverse[1] * ax1) + (inverse[4] * bx1) + (inverse[7] * cx1); localTransform.tx = (inverse[2] * ax1) + (inverse[5] * bx1) + (inverse[8] * cx1); localTransform.b = (inverse[0] * ay1) + (inverse[3] * by1) + (inverse[6] * cy1); localTransform.d = (inverse[1] * ay1) + (inverse[4] * by1) + (inverse[7] * cy1); localTransform.ty = (inverse[2] * ay1) + (inverse[5] * by1) + (inverse[8] * cy1); transform.setFromMatrix(localTransform); return this; } /** * Updates the transform of the conic, and if changed updates the geometry data. * * @override */ updateTransform(): void { const ret = super.updateTransform(); if (this._transformID !== this.transform._worldID) { this.updateConic(); this._transformID = this.transform._worldID; } return ret; } }
the_stack
import React, {useState, useEffect, useContext} from "react"; import {ModelingContext} from "../../../../util/modeling-context"; import {Modal, Input, Select, Icon, Card, Dropdown} from "antd"; import {DownOutlined} from "@ant-design/icons"; import DropDownWithSearch from "../../../common/dropdown-with-search/dropdownWithSearch"; import {MLButton, MLTooltip} from "@marklogic/design-system"; import styles from "./add-edit-relationship.module.scss"; // import graphConfig from "../../../../config/graph-vis.config"; import oneToManyIcon from "../../../../assets/one-to-many.svg"; import oneToOneIcon from "../../../../assets/one-to-one.svg"; import {faTrashAlt, faChevronDown, faChevronRight} from "@fortawesome/free-solid-svg-icons"; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {ModelingTooltips} from "../../../../config/tooltips.config"; import ConfirmationModal from "../../../confirmation-modal/confirmation-modal"; import {ConfirmationType} from "../../../../types/common-types"; import {getSystemInfo} from "../../../../api/environment"; import {entityReferences} from "../../../../api/modeling"; import { PropertyOptions, PropertyType, EntityModified } from "../../../../types/modeling-types"; type Props = { openRelationshipModal: boolean; setOpenRelationshipModal: (boolean) => (void); isEditing: boolean; relationshipInfo: any; entityTypes: any; relationshipModalVisible: any; toggleRelationshipModal: any; updateSavedEntity: any; canReadEntityModel: any; canWriteEntityModel: any; entityMetadata: any; } const {Option} = Select; const NAME_REGEX = new RegExp("^[A-Za-z][A-Za-z0-9_-]*$"); const AddEditRelationship: React.FC<Props> = (props) => { const headerText = !props.isEditing ? ModelingTooltips.addRelationshipHeader : ""; const [relationshipName, setRelationshipName] = useState(""); //set default value when editing const [joinPropertyValue, setJoinPropertyValue] = useState(""); //set default value when editing const [submitClicked, setSubmitClicked] = useState(false); const [oneToManySelected, setOneToManySelected] = useState(false); //set default value when editing const [errorMessage, setErrorMessage] = useState(""); const [targetNodeJoinProperties, setTargetNodeJoinProperties] = useState<any[]>([]); const {modelingOptions, updateEntityModified} = useContext(ModelingContext); const [loading, toggleLoading] = useState(false); const [showConfirmModal, toggleConfirmModal] = useState(false); const [confirmType, setConfirmType] = useState<ConfirmationType>(ConfirmationType.Identifer); const [confirmBoldTextArray, setConfirmBoldTextArray] = useState<string[]>([]); const [stepValuesArray, setStepValuesArray] = useState<string[]>([]); const [modifiedEntity, setModifiedEntity] = useState({entityName: "", modelDefinition: ""}); const [targetEntityName, setTargetEntityName] = useState(""); const [targetEntityColor, setTargetEntityColor] = useState(""); const [emptyTargetEntity, setEmptyTargetEntity] = useState(false); const [displayEntityList, setDisplayEntityList] = useState(false); const [displaySourceMenu, setDisplaySourceMenu] = useState(false); const [optionalCollapsed, setOptionalCollapsed] = useState(true); const [cardinalityToggled, setCardinalityToggled] = useState(false); const initRelationship = (sourceEntityIdx) => { let sourceEntityDetails = props.entityTypes[sourceEntityIdx]; if (props.relationshipInfo.relationshipName !== "") { setRelationshipName(props.relationshipInfo.relationshipName); setErrorMessage(""); } else { setRelationshipName(""); setErrorMessage(ModelingTooltips.relationshipEmpty); } if (props.relationshipInfo.joinPropertyName && props.relationshipInfo.joinPropertyName !== "undefined") { setJoinPropertyValue(props.relationshipInfo.joinPropertyName); setOptionalCollapsed(false); } else { setJoinPropertyValue(""); } setTargetEntityName(props.relationshipInfo.targetNodeName); setTargetEntityColor(props.relationshipInfo.targetNodeColor); setOneToManySelected(false); if (sourceEntityDetails.model.definitions[props.relationshipInfo.sourceNodeName].properties[props.relationshipInfo.relationshipName]?.hasOwnProperty("items")) { //set cardinality selection to "multiple" setOneToManySelected(true); } }; useEffect(() => { if (props.entityTypes.length > 0 && JSON.stringify(props.relationshipInfo) !== "{}") { let targetEntityIdx = props.entityTypes.findIndex(obj => obj.entityName === props.relationshipInfo.targetNodeName); let sourceEntityIdx = props.entityTypes.findIndex(obj => obj.entityName === props.relationshipInfo.sourceNodeName); initRelationship(sourceEntityIdx); if (props.relationshipInfo.targetNodeName !== "Select target entity type*") { setEmptyTargetEntity(false); createJoinMenu(targetEntityIdx); } else { setEmptyTargetEntity(true); } } }, [props.entityTypes, props.relationshipInfo]); useEffect(() => { if (!props.relationshipModalVisible) { toggleLoading(false); props.setOpenRelationshipModal(false); props.toggleRelationshipModal(true); } }, [props.relationshipModalVisible]); const getPropertyType = (joinPropName, targetNodeName) => { let targetEntityIdx = props.entityTypes.findIndex(obj => obj.entityName === targetNodeName); let targetEntityDetails = props.entityTypes[targetEntityIdx]; if (joinPropName && joinPropName !== "") { return targetEntityDetails.model.definitions[targetNodeName].properties[joinPropName].datatype; } else { return ""; } }; const createPropertyDefinitionPayload = (propertyOptions: PropertyOptions) => { let multiple = propertyOptions.multiple === "yes" ? true : false; let facetable = propertyOptions.facetable; let sortable = propertyOptions.sortable; if (propertyOptions.propertyType === PropertyType.RelatedEntity && !multiple) { let externalEntity = props.entityTypes.find(entity => entity.entityName === propertyOptions.type); if (propertyOptions.joinPropertyType === "") { return { datatype: "string", relatedEntityType: externalEntity.entityTypeId, joinPropertyName: propertyOptions.joinPropertyName, }; } else { return { datatype: propertyOptions.joinPropertyType, relatedEntityType: externalEntity.entityTypeId, joinPropertyName: propertyOptions.joinPropertyName, }; } } else if (propertyOptions.propertyType === PropertyType.RelatedEntity && multiple) { let externalEntity = props.entityTypes.find(entity => entity.entityName === propertyOptions.type); if (propertyOptions.joinPropertyType === "") { return { datatype: "array", facetable: facetable, sortable: sortable, items: { datatype: "string", relatedEntityType: externalEntity.entityTypeId, joinPropertyName: propertyOptions.joinPropertyName, } }; } else { return { datatype: "array", facetable: facetable, sortable: sortable, items: { datatype: propertyOptions.joinPropertyType, relatedEntityType: externalEntity.entityTypeId, joinPropertyName: propertyOptions.joinPropertyName, } }; } } else if (propertyOptions.propertyType === PropertyType.Structured && !multiple) { return { $ref: "#/definitions/" + propertyOptions.type, }; } else if (propertyOptions.propertyType === PropertyType.Structured && multiple) { return { datatype: "array", facetable: facetable, sortable: sortable, items: { $ref: "#/definitions/" + propertyOptions.type, } }; } else if (propertyOptions.propertyType === PropertyType.Basic && multiple) { return { datatype: "array", facetable: facetable, sortable: sortable, items: { datatype: propertyOptions.type, collation: "http://marklogic.com/collation/codepoint", } }; } else if (propertyOptions.propertyType === PropertyType.Basic && !multiple) { return { datatype: propertyOptions.type, facetable: facetable, sortable: sortable, collation: "http://marklogic.com/collation/codepoint" }; } }; const editPropertyUpdateDefinition = async (entityIdx: number, definitionName: string, propertyName: string, editPropertyOptions) => { let parseName = definitionName.split(","); let parseDefinitionName = parseName[parseName.length - 1]; let updatedDefinitions = {...props.entityTypes[entityIdx].model.definitions}; let entityTypeDefinition = updatedDefinitions[parseDefinitionName]; let newProperty = createPropertyDefinitionPayload(editPropertyOptions.propertyOptions); entityTypeDefinition["properties"][propertyName] = newProperty; if (editPropertyOptions.propertyOptions.identifier === "yes") { entityTypeDefinition.primaryKey = editPropertyOptions.name; } else if (entityTypeDefinition.hasOwnProperty("primaryKey") && entityTypeDefinition.primaryKey === propertyName) { delete entityTypeDefinition.primaryKey; } if (editPropertyOptions.propertyOptions.pii === "yes") { let index = entityTypeDefinition.pii?.indexOf(propertyName); if (index > -1) { entityTypeDefinition.pii[index] = editPropertyOptions.name; } else { if (entityTypeDefinition.hasOwnProperty("pii")) { entityTypeDefinition.pii.push(editPropertyOptions.name); } else { entityTypeDefinition.pii = [editPropertyOptions.name]; } } } else { let index = entityTypeDefinition.pii?.indexOf(propertyName); if (index > -1) { entityTypeDefinition.pii.splice(index, 1); } } if (propertyName !== editPropertyOptions.name) { let reMapDefinition = Object.keys(entityTypeDefinition["properties"]).map((key) => { const newKey = key === propertyName ? editPropertyOptions.name : key; const value = key === propertyName ? newProperty : entityTypeDefinition["properties"][key]; return {[newKey]: value}; }); entityTypeDefinition["properties"] = reMapDefinition.reduce((a, b) => Object.assign({}, a, b)); if (entityTypeDefinition.hasOwnProperty("required") && entityTypeDefinition.required.some(value => value === propertyName)) { let index = entityTypeDefinition.required.indexOf(propertyName); entityTypeDefinition.required[index] = editPropertyOptions.name; } if (entityTypeDefinition.hasOwnProperty("rangeIndex") && entityTypeDefinition.rangeIndex.some(value => value === propertyName)) { let index = entityTypeDefinition.rangeIndex.indexOf(propertyName); entityTypeDefinition.rangeIndex[index] = editPropertyOptions.name; } if (entityTypeDefinition.hasOwnProperty("pathRangeIndex") && entityTypeDefinition.pathRangeIndex.some(value => value === propertyName)) { let index = entityTypeDefinition.pathRangeIndex.indexOf(propertyName); entityTypeDefinition.pathRangeIndex[index] = editPropertyOptions.name; } if (entityTypeDefinition.hasOwnProperty("elementRangeIndex") && entityTypeDefinition.elementRangeIndex.some(value => value === propertyName)) { let index = entityTypeDefinition.elementRangeIndex.indexOf(propertyName); entityTypeDefinition.elementRangeIndex[index] = editPropertyOptions.name; } if (entityTypeDefinition.hasOwnProperty("wordLexicon") && entityTypeDefinition.wordLexicon.some(value => value === propertyName)) { let index = entityTypeDefinition.wordLexicon.indexOf(propertyName); entityTypeDefinition.wordLexicon[index] = editPropertyOptions.name; } } updatedDefinitions[parseDefinitionName] = entityTypeDefinition; let modifiedEntityStruct: EntityModified = { entityName: definitionName, modelDefinition: updatedDefinitions }; if (props.updateSavedEntity) { await props.updateSavedEntity([modifiedEntityStruct]); } return modifiedEntityStruct; }; const onCancel = () => { if (!loading) { setErrorMessage(""); props.toggleRelationshipModal(true); props.setOpenRelationshipModal(false); setSubmitClicked(false); setTargetEntityName(""); setTargetEntityColor(""); setJoinPropertyValue(""); setRelationshipName(""); setCardinalityToggled(false); setOptionalCollapsed(true); } }; const onSubmit = () => { setSubmitClicked(true); if (errorMessage === "" && !emptyTargetEntity) { let sourceEntityIdx = props.entityTypes.findIndex(obj => obj.entityName === props.relationshipInfo.sourceNodeName); let sourceProperties = props.entityTypes[sourceEntityIdx].model.definitions[props.relationshipInfo.sourceNodeName].properties; let propertyNamesArray = props.isEditing ? Object.keys(sourceProperties).filter(propertyName => propertyName !== props.relationshipInfo.relationshipName) : Object.keys(sourceProperties); let joinPropertyVal = joinPropertyValue === "None" ? "" : joinPropertyValue; if (propertyNamesArray.includes(relationshipName) || props.relationshipInfo.sourceNodeName === relationshipName) { setErrorMessage("name-error"); } else { const newEditPropertyOptions = { name: relationshipName, isEdit: props.isEditing, propertyOptions: { facetable: false, identifier: "no", joinPropertyName: joinPropertyVal, joinPropertyType: getPropertyType(joinPropertyVal, targetEntityName), multiple: oneToManySelected ? "yes" : "no", pii: "no", propertyType: "relatedEntity", sortable: false, type: targetEntityName } }; //do not enter loading save if no changes have been made if (joinPropertyValue === props.relationshipInfo.joinPropertyName && relationshipName === props.relationshipInfo.relationshipName && !cardinalityToggled) { toggleLoading(false); props.setOpenRelationshipModal(false); } else { toggleLoading(true); let entityModified: any = editPropertyUpdateDefinition(sourceEntityIdx, props.relationshipInfo.sourceNodeName, props.relationshipInfo.relationshipName, newEditPropertyOptions); updateEntityModified(entityModified); } setCardinalityToggled(false); setOptionalCollapsed(true); setErrorMessage(""); setSubmitClicked(false); } } }; const createJoinMenu = (entityIdx) => { let targetEntityDetails, entityUpdated, modelUpdated, menuProps, model; targetEntityDetails = props.entityTypes[entityIdx]; model = targetEntityDetails.model.definitions[props.relationshipInfo.targetNodeName]; entityUpdated = modelingOptions.modifiedEntitiesArray.find(ent => ent.entityName === props.relationshipInfo.targetNodeName); // Modified model data (if present) if (entityUpdated) { modelUpdated = entityUpdated.modelDefinition[props.relationshipInfo.targetNodeName]; } menuProps = getJoinMenuProps(model, modelUpdated); menuProps.unshift({value: "None", label: "None", type: "string"}); if (menuProps) { setTargetNodeJoinProperties(menuProps); } else { setTargetNodeJoinProperties([]); } }; const getJoinMenuProps = (model, modelUpdated) => { let alreadyAdded: string[] = [], result; // Check each property from saved model and build menu items if (model) { result = Object.keys(model.properties).map(key => { alreadyAdded.push(key); // Structured property case if (model.properties[key].hasOwnProperty("$ref")) { return { value: key, label: key, type: "", // TODO disabled: true, // TODO Support structure properties // children: getJoinProps(...) }; } else if (model.properties[key]["datatype"] === "array") { // Array property case return { value: key, label: key, type: "", // TODO disabled: true }; } else { // Default case return { value: key, label: key, type: model.properties[key].datatype }; } }); } // Include any new properties from updated model object if (modelUpdated) { Object.keys(modelUpdated?.properties).map(key => { if (!alreadyAdded.includes(key)) { result.push({ value: key, label: key, type: modelUpdated.properties[key].datatype, disabled: true }); } }); } return result; }; const toggleCardinality = () => { if (oneToManySelected) { setOneToManySelected(false); } else { setOneToManySelected(true); } setCardinalityToggled(!cardinalityToggled); }; const handleChange = (event) => { if (event.target.id === "relationship") { setRelationshipName(event.target.value); if (event.target.value === "") { setErrorMessage(ModelingTooltips.relationshipEmpty); } else if (!NAME_REGEX.test(event.target.value)) { setErrorMessage(ModelingTooltips.nameRegex); } else { setErrorMessage(""); } } }; const handleOptionSelect = (value) => { setJoinPropertyValue(value); }; function handleMenuClick(event) { let model, menuProps, entityName, entityIdx; setEmptyTargetEntity(false); //update join property dropdown with new target entity properties and clear existing value entityName = event; entityIdx = props.entityTypes.findIndex(entity => entity.entityName === entityName); model = props.entityTypes[entityIdx].model.definitions[entityName]; menuProps = getJoinMenuProps(model, ""); menuProps.unshift({value: "None", label: "None", type: "string"}); if (menuProps) { setTargetNodeJoinProperties(menuProps); } else { setTargetNodeJoinProperties([]); } setJoinPropertyValue(""); //update target entity name and color, setTargetEntityName(entityName); if (props.entityTypes[entityIdx].model.hubCentral && props.entityTypes[entityIdx].model.hubCentral.modeling.color) { //revise when colors are retrieved from backend setTargetEntityColor(props.entityTypes[entityIdx].model.hubCentral.modeling.color); } else { setTargetEntityColor("#EEEFF1"); //assigning default color if entity is not assigned a color yet } setDisplaySourceMenu(prev => false); setDisplayEntityList(prev => false); } //format entity types to tuples for DropDownWithSearch to work const entityTypesToTuples = (entityTypes) => { let entityTuples:any = []; entityTypes.map(entity => { entityTuples.push({value: entity.entityName, key: entity.entityName, struct: false}); }); return entityTuples; }; const toggleDropdown = () => { setDisplayEntityList(!displayEntityList); }; const toggleOptionalIcon = () => { setOptionalCollapsed(!optionalCollapsed); }; const menu = ( <DropDownWithSearch displayMenu={displaySourceMenu} setDisplayMenu={setDisplaySourceMenu} setDisplaySelectList={setDisplayEntityList} displaySelectList={displayEntityList} itemValue={""} onItemSelect={handleMenuClick} srcData={entityTypesToTuples(props.entityTypes)} propName={""} handleDropdownMenu={{}} indentList={null} modelling={true} /> ); const foreignKeyDropdown = ( <Select placeholder="Select foreign key" id="foreignKey-dropdown" data-testid="foreignKey-dropdown" disabled={emptyTargetEntity} value={joinPropertyValue ? joinPropertyValue : undefined} onChange={value => handleOptionSelect(value)} className={styles.foreignKeyDropdown} showArrow={true} size={"default"} > { targetNodeJoinProperties.length > 0 && targetNodeJoinProperties.map((prop, index) => ( <Option key={`${prop.label}-option`} value={prop.value} disabled={prop.disabled} aria-label={`${prop.label}-option`}>{prop.label === "None" ? "- " + prop.label + " -" : prop.label}</Option> )) } </Select> ); const deleteEntityProperty= async () => { let entityName = props.relationshipInfo.sourceNodeName; let propertyName = props.relationshipInfo.relationshipName; const response = await entityReferences(entityName, propertyName); if (response !== undefined && response["status"] === 200) { let newConfirmType = ConfirmationType.DeletePropertyWarn; let boldText: string[] = [propertyName]; if (response["data"]["entityNamesWithForeignKeyReferences"].length > 0) { boldText.push(entityName); newConfirmType = ConfirmationType.DeleteEntityPropertyWithForeignKeyReferences; setStepValuesArray(response["data"]["entityNamesWithForeignKeyReferences"]); } else if (response["data"]["stepNames"].length > 0) { boldText.push(entityName); newConfirmType = ConfirmationType.DeletePropertyStepWarn; setStepValuesArray(response["data"]["stepNames"]); } setConfirmBoldTextArray(boldText); setConfirmType(newConfirmType); toggleConfirmModal(true); } let sourceEntityName = props.relationshipInfo.sourceNodeName; let entityTypeDefinition; let updatedDefinitions; for (let i = 0; i < props.entityTypes.length; i++) { if (props.entityTypes[i].entityName === sourceEntityName) { updatedDefinitions = {...props.entityTypes[i].model}; entityTypeDefinition = props.entityTypes[i].model.definitions[sourceEntityName]; } } delete entityTypeDefinition["properties"][propertyName]; updatedDefinitions[sourceEntityName] = entityTypeDefinition; let entityModifiedInfo: EntityModified = { entityName: sourceEntityName, modelDefinition: updatedDefinitions.definitions }; setModifiedEntity(entityModifiedInfo); updateEntityModified(modifiedEntity); }; const modalFooter = <div className={styles.modalFooter}> <div className={styles.deleteTooltip}> <MLTooltip title={ModelingTooltips.deleteRelationshipIcon} placement="top"> <i key="last" role="delete-entity button" data-testid={"delete-relationship"}> <FontAwesomeIcon className={!props.canWriteEntityModel && props.canReadEntityModel ? styles.iconTrashReadOnly : styles.deleteIcon} size="lg" icon={faTrashAlt} onClick={(event) => { if (!props.canWriteEntityModel && props.canReadEntityModel) { return event.preventDefault(); } else { deleteEntityProperty(); } }} /> </i> </MLTooltip> </div> <MLButton aria-label="relationship-modal-cancel" size="default" onClick={onCancel} >Cancel</MLButton> <MLButton aria-label="relationship-modal-submit" form="property-form" type="primary" htmlType="submit" size="default" loading={loading} onClick={onSubmit} >{props.isEditing ? "Save" : "Add"}</MLButton> </div>; const confirmAction = async () => { await props.updateSavedEntity([modifiedEntity]); await getSystemInfo(); toggleConfirmModal(false); }; return (<Modal visible={props.openRelationshipModal} title={<span aria-label="relationshipHeader">{props.isEditing ? "Edit Relationship" : "Add a Relationship"}</span>} width="960px" onCancel={onCancel} footer={modalFooter} maskClosable={false} destroyOnClose={true} > <div aria-label="relationshipModal" id="relationshipModal" className={styles.relationshipModalContainer}> { <div aria-label="header-message"> {headerText} </div> } <div aria-label="relationshipActions" className={styles.relationshipDisplay}> <div className={styles.nodeDisplay}> <span className={styles.nodeLabel}>SOURCE</span> <Card style={{width: 204, backgroundColor: props.relationshipInfo.sourceNodeColor}}> <p data-testid={`${props.relationshipInfo.sourceNodeName}-sourceNodeName`} className={styles.entityName}><b>{props.relationshipInfo.sourceNodeName}</b></p> </Card> </div> <div className={styles.relationshipInputContainer}> <Input id="relationship" placeholder="Relationship*" value={relationshipName} onChange={handleChange} size={"small"} // disabled={!canReadWrite} className={styles.relationshipInput} aria-label="relationship-textarea" style={errorMessage && submitClicked? {border: "solid 1px #C00"} : {}} /> {errorMessage && submitClicked? <MLTooltip title={errorMessage === "name-error" ? ModelingTooltips.duplicatePropertyError(relationshipName) : errorMessage} placement={"bottom"}><Icon aria-label="error-circle" type="exclamation-circle" theme="filled" className={styles.errorIcon}/></MLTooltip> : ""} <MLTooltip title={ModelingTooltips.relationshipNameInfo(props.relationshipInfo.sourceNodeName)} placement={"bottom"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled"/> </MLTooltip> </div> <hr className={styles.horizontalLine}></hr> <MLTooltip title={ModelingTooltips.cardinalityButton} placement={"bottom"}> <MLButton className={styles.cardinalityButton} data-testid="cardinalityButton" onClick={() => toggleCardinality()}> {oneToManySelected ? <img data-testid="oneToManyIcon" className={styles.oneToManyIcon} src={oneToManyIcon} alt={""} onClick={() => toggleCardinality()}/> : <img data-testid="oneToOneIcon" className={styles.oneToOneIcon} src={oneToOneIcon} alt={""} onClick={() => toggleCardinality()}/>} </MLButton> </MLTooltip> <div className={styles.nodeDisplay}> <span className={styles.nodeLabel}>TARGET</span> <div className={submitClicked && emptyTargetEntity ? styles.targetEntityErrorContainer : styles.targetEntityContainer}> <Card style={{width: 204, backgroundColor: targetEntityColor, marginLeft: "-2px"}}> <p data-testid={`${targetEntityName}-targetNodeName`} className={styles.entityName}>{emptyTargetEntity ? targetEntityName : <b>{targetEntityName}</b>}</p> </Card> {!props.isEditing ? <Dropdown overlay={menu} overlayClassName={styles.dropdownMenu} trigger={["click"]} placement="bottomRight"> <span className={styles.dropdownArrow}> { <DownOutlined data-testid={"targetEntityDropdown"} onClick={(e) => toggleDropdown()}/> } </span> </Dropdown> : null } </div> {submitClicked && emptyTargetEntity ? <span className={styles.targetEntityErrorMsg}>{ModelingTooltips.targetEntityEmpty}</span> : null} </div> </div> <div className={styles.toggleOptional}> {optionalCollapsed ? <FontAwesomeIcon className={styles.optionalIcon} icon={faChevronRight} size={"sm"} onClick = {(e) => toggleOptionalIcon()}/> : <FontAwesomeIcon className={styles.optionalIcon} icon={faChevronDown} size={"sm"} onClick = {(e) => toggleOptionalIcon()}/> } <span className={styles.optionalText} onClick = {(e) => toggleOptionalIcon()}>Optional</span> </div> { !optionalCollapsed && ( <div className={styles.foreignKeyContainer}> <span className={styles.foreignKeyText}>You can select the foreign key now or later:</span> <div className={styles.foreignKeyDropdownContainer}> {foreignKeyDropdown} <MLTooltip title={ModelingTooltips.foreignKeyInfo} placement={"bottom"}> <Icon type="question-circle" data-testid={"foreign-key-tooltip"}className={styles.foreignKeyQuestionCircle} theme="filled"/> </MLTooltip> </div> </div> ) } <div className={styles.requiredFootnote}>* Required</div> </div> <ConfirmationModal isVisible={showConfirmModal} type={confirmType} boldTextArray={confirmBoldTextArray} arrayValues={stepValuesArray} toggleModal={toggleConfirmModal} confirmAction={confirmAction} /> </Modal>); }; export default AddEditRelationship;
the_stack
import { schemas, SchemaValidator } from '@0x/json-schemas'; import { assetDataUtils, orderCalculationUtils, SignedOrder } from '@0x/order-utils'; import { RFQTFirmQuote, RFQTIndicativeQuote, TakerRequestQueryParams } from '@0x/quote-server'; import { ERC20AssetData } from '@0x/types'; import { BigNumber } from '@0x/utils'; import Axios, { AxiosInstance } from 'axios'; import { Agent as HttpAgent } from 'http'; import { Agent as HttpsAgent } from 'https'; import { constants } from '../constants'; import { LogFunction, MarketOperation, RfqtMakerAssetOfferings, RfqtRequestOpts } from '../types'; import { ONE_SECOND_MS } from './market_operation_utils/constants'; import { RfqMakerBlacklist } from './rfq_maker_blacklist'; // tslint:disable-next-line: custom-no-magic-numbers const KEEP_ALIVE_TTL = 5 * 60 * ONE_SECOND_MS; export const quoteRequestorHttpClient: AxiosInstance = Axios.create({ httpAgent: new HttpAgent({ keepAlive: true, timeout: KEEP_ALIVE_TTL }), httpsAgent: new HttpsAgent({ keepAlive: true, timeout: KEEP_ALIVE_TTL }), }); const MAKER_TIMEOUT_STREAK_LENGTH = 10; const MAKER_TIMEOUT_BLACKLIST_DURATION_MINUTES = 10; const rfqMakerBlacklist = new RfqMakerBlacklist(MAKER_TIMEOUT_STREAK_LENGTH, MAKER_TIMEOUT_BLACKLIST_DURATION_MINUTES); /** * Request quotes from RFQ-T providers */ function getTokenAddressOrThrow(assetData: string): string { const decodedAssetData = assetDataUtils.decodeAssetDataOrThrow(assetData); if (decodedAssetData.hasOwnProperty('tokenAddress')) { // type cast necessary here as decodeAssetDataOrThrow returns // an AssetData object, which doesn't necessarily contain a // token address. (it could possibly be a StaticCallAssetData, // which lacks an address.) so we'll just assume it's a token // here. should be safe, with the enclosing guard condition // and subsequent error. // tslint:disable-next-line:no-unnecessary-type-assertion return (decodedAssetData as ERC20AssetData).tokenAddress; } throw new Error(`Decoded asset data (${JSON.stringify(decodedAssetData)}) does not contain a token address`); } function hasExpectedAssetData( expectedMakerAssetData: string, expectedTakerAssetData: string, makerAssetDataInQuestion: string, takerAssetDataInQuestion: string, ): boolean { const hasExpectedMakerAssetData = makerAssetDataInQuestion.toLowerCase() === expectedMakerAssetData.toLowerCase(); const hasExpectedTakerAssetData = takerAssetDataInQuestion.toLowerCase() === expectedTakerAssetData.toLowerCase(); return hasExpectedMakerAssetData && hasExpectedTakerAssetData; } function convertIfAxiosError(error: any): Error | object /* axios' .d.ts has AxiosError.toJSON() returning object */ { if (error.hasOwnProperty('isAxiosError') && error.isAxiosError) { const { message, name, config } = error; const { headers, timeout, httpsAgent } = config; const { keepAlive, keepAliveMsecs, sockets } = httpsAgent; const socketCounts: { [key: string]: number } = {}; for (const socket of Object.keys(sockets)) { socketCounts[socket] = sockets[socket].length; } return { message, name, config: { headers, timeout, httpsAgent: { keepAlive, keepAliveMsecs, socketCounts, }, }, }; } else { return error; } } export class QuoteRequestor { private readonly _schemaValidator: SchemaValidator = new SchemaValidator(); private readonly _orderSignatureToMakerUri: { [orderSignature: string]: string } = {}; public static makeQueryParameters( takerAddress: string, marketOperation: MarketOperation, makerAssetData: string, takerAssetData: string, assetFillAmount: BigNumber, comparisonPrice?: BigNumber, ): TakerRequestQueryParams { const buyTokenAddress = getTokenAddressOrThrow(makerAssetData); const sellTokenAddress = getTokenAddressOrThrow(takerAssetData); const { buyAmountBaseUnits, sellAmountBaseUnits } = marketOperation === MarketOperation.Buy ? { buyAmountBaseUnits: assetFillAmount, sellAmountBaseUnits: undefined, } : { sellAmountBaseUnits: assetFillAmount, buyAmountBaseUnits: undefined, }; const requestParamsWithBigNumbers: Pick< TakerRequestQueryParams, 'buyTokenAddress' | 'sellTokenAddress' | 'takerAddress' | 'comparisonPrice' > = { takerAddress, comparisonPrice: comparisonPrice === undefined ? undefined : comparisonPrice.toString(), buyTokenAddress, sellTokenAddress, }; // convert BigNumbers to strings // so they are digestible by axios if (sellAmountBaseUnits) { return { ...requestParamsWithBigNumbers, sellAmountBaseUnits: sellAmountBaseUnits.toString(), }; } else if (buyAmountBaseUnits) { return { ...requestParamsWithBigNumbers, buyAmountBaseUnits: buyAmountBaseUnits.toString(), }; } else { throw new Error('Neither "buyAmountBaseUnits" or "sellAmountBaseUnits" were defined'); } } constructor( private readonly _rfqtAssetOfferings: RfqtMakerAssetOfferings, private readonly _warningLogger: LogFunction = constants.DEFAULT_WARNING_LOGGER, private readonly _infoLogger: LogFunction = constants.DEFAULT_INFO_LOGGER, private readonly _expiryBufferMs: number = constants.DEFAULT_SWAP_QUOTER_OPTS.expiryBufferMs, ) { rfqMakerBlacklist.infoLogger = this._infoLogger; } public async requestRfqtFirmQuotesAsync( makerAssetData: string, takerAssetData: string, assetFillAmount: BigNumber, marketOperation: MarketOperation, comparisonPrice: BigNumber | undefined, options: RfqtRequestOpts, ): Promise<RFQTFirmQuote[]> { const _opts: RfqtRequestOpts = { ...constants.DEFAULT_RFQT_REQUEST_OPTS, ...options }; if ( _opts.takerAddress === undefined || _opts.takerAddress === '' || _opts.takerAddress === '0x' || !_opts.takerAddress || _opts.takerAddress === constants.NULL_ADDRESS ) { throw new Error('RFQ-T firm quotes require the presence of a taker address'); } const firmQuoteResponses = await this._getQuotesAsync<RFQTFirmQuote>( // not yet BigNumber makerAssetData, takerAssetData, assetFillAmount, marketOperation, comparisonPrice, _opts, 'firm', ); const result: RFQTFirmQuote[] = []; firmQuoteResponses.forEach(firmQuoteResponse => { const orderWithStringInts = firmQuoteResponse.response.signedOrder; try { const hasValidSchema = this._schemaValidator.isValid(orderWithStringInts, schemas.signedOrderSchema); if (!hasValidSchema) { throw new Error('Order not valid'); } } catch (err) { this._warningLogger(orderWithStringInts, `Invalid RFQ-t order received, filtering out. ${err.message}`); return; } if ( !hasExpectedAssetData( makerAssetData, takerAssetData, orderWithStringInts.makerAssetData.toLowerCase(), orderWithStringInts.takerAssetData.toLowerCase(), ) ) { this._warningLogger(orderWithStringInts, 'Unexpected asset data in RFQ-T order, filtering out'); return; } if (orderWithStringInts.takerAddress.toLowerCase() !== _opts.takerAddress.toLowerCase()) { this._warningLogger(orderWithStringInts, 'Unexpected takerAddress in RFQ-T order, filtering out'); return; } const orderWithBigNumberInts: SignedOrder = { ...orderWithStringInts, makerAssetAmount: new BigNumber(orderWithStringInts.makerAssetAmount), takerAssetAmount: new BigNumber(orderWithStringInts.takerAssetAmount), makerFee: new BigNumber(orderWithStringInts.makerFee), takerFee: new BigNumber(orderWithStringInts.takerFee), expirationTimeSeconds: new BigNumber(orderWithStringInts.expirationTimeSeconds), salt: new BigNumber(orderWithStringInts.salt), }; if ( orderCalculationUtils.willOrderExpire( orderWithBigNumberInts, this._expiryBufferMs / constants.ONE_SECOND_MS, ) ) { this._warningLogger(orderWithBigNumberInts, 'Expiry too soon in RFQ-T order, filtering out'); return; } // Store makerUri for looking up later this._orderSignatureToMakerUri[orderWithBigNumberInts.signature] = firmQuoteResponse.makerUri; // Passed all validation, add it to result result.push({ signedOrder: orderWithBigNumberInts }); return; }); return result; } public async requestRfqtIndicativeQuotesAsync( makerAssetData: string, takerAssetData: string, assetFillAmount: BigNumber, marketOperation: MarketOperation, comparisonPrice: BigNumber | undefined, options: RfqtRequestOpts, ): Promise<RFQTIndicativeQuote[]> { const _opts: RfqtRequestOpts = { ...constants.DEFAULT_RFQT_REQUEST_OPTS, ...options }; // Originally a takerAddress was required for indicative quotes, but // now we've eliminated that requirement. @0x/quote-server, however, // is still coded to expect a takerAddress. So if the client didn't // send one, just use the null address to satisfy the quote server's // expectations. if (!_opts.takerAddress) { _opts.takerAddress = constants.NULL_ADDRESS; } const responsesWithStringInts = await this._getQuotesAsync<RFQTIndicativeQuote>( // not yet BigNumber makerAssetData, takerAssetData, assetFillAmount, marketOperation, comparisonPrice, _opts, 'indicative', ); const validResponsesWithStringInts = responsesWithStringInts.filter(result => { const response = result.response; if (!this._isValidRfqtIndicativeQuoteResponse(response)) { this._warningLogger(response, 'Invalid RFQ-T indicative quote received, filtering out'); return false; } if ( !hasExpectedAssetData(makerAssetData, takerAssetData, response.makerAssetData, response.takerAssetData) ) { this._warningLogger(response, 'Unexpected asset data in RFQ-T indicative quote, filtering out'); return false; } return true; }); const validResponses = validResponsesWithStringInts.map(result => { const response = result.response; return { ...response, makerAssetAmount: new BigNumber(response.makerAssetAmount), takerAssetAmount: new BigNumber(response.takerAssetAmount), expirationTimeSeconds: new BigNumber(response.expirationTimeSeconds), }; }); const responses = validResponses.filter(response => { if (this._isExpirationTooSoon(response.expirationTimeSeconds)) { this._warningLogger(response, 'Expiry too soon in RFQ-T indicative quote, filtering out'); return false; } return true; }); return responses; } /** * Given an order signature, returns the makerUri that the order originated from */ public getMakerUriForOrderSignature(orderSignature: string): string | undefined { return this._orderSignatureToMakerUri[orderSignature]; } private _isValidRfqtIndicativeQuoteResponse(response: RFQTIndicativeQuote): boolean { const hasValidMakerAssetAmount = response.makerAssetAmount !== undefined && this._schemaValidator.isValid(response.makerAssetAmount, schemas.wholeNumberSchema); const hasValidTakerAssetAmount = response.takerAssetAmount !== undefined && this._schemaValidator.isValid(response.takerAssetAmount, schemas.wholeNumberSchema); const hasValidMakerAssetData = response.makerAssetData !== undefined && this._schemaValidator.isValid(response.makerAssetData, schemas.hexSchema); const hasValidTakerAssetData = response.takerAssetData !== undefined && this._schemaValidator.isValid(response.takerAssetData, schemas.hexSchema); const hasValidExpirationTimeSeconds = response.expirationTimeSeconds !== undefined && this._schemaValidator.isValid(response.expirationTimeSeconds, schemas.wholeNumberSchema); if ( hasValidMakerAssetAmount && hasValidTakerAssetAmount && hasValidMakerAssetData && hasValidTakerAssetData && hasValidExpirationTimeSeconds ) { return true; } return false; } private _makerSupportsPair(makerUrl: string, makerAssetData: string, takerAssetData: string): boolean { const makerTokenAddress = getTokenAddressOrThrow(makerAssetData); const takerTokenAddress = getTokenAddressOrThrow(takerAssetData); for (const assetPair of this._rfqtAssetOfferings[makerUrl]) { if ( (assetPair[0] === makerTokenAddress && assetPair[1] === takerTokenAddress) || (assetPair[0] === takerTokenAddress && assetPair[1] === makerTokenAddress) ) { return true; } } return false; } private _isExpirationTooSoon(expirationTimeSeconds: BigNumber): boolean { const expirationTimeMs = expirationTimeSeconds.times(constants.ONE_SECOND_MS); const currentTimeMs = new BigNumber(Date.now()); return expirationTimeMs.isLessThan(currentTimeMs.plus(this._expiryBufferMs)); } private async _getQuotesAsync<ResponseT>( makerAssetData: string, takerAssetData: string, assetFillAmount: BigNumber, marketOperation: MarketOperation, comparisonPrice: BigNumber | undefined, options: RfqtRequestOpts, quoteType: 'firm' | 'indicative', ): Promise<Array<{ response: ResponseT; makerUri: string }>> { const requestParams = QuoteRequestor.makeQueryParameters( options.takerAddress, marketOperation, makerAssetData, takerAssetData, assetFillAmount, comparisonPrice, ); const result: Array<{ response: ResponseT; makerUri: string }> = []; await Promise.all( Object.keys(this._rfqtAssetOfferings).map(async url => { const isBlacklisted = rfqMakerBlacklist.isMakerBlacklisted(url); const partialLogEntry = { url, quoteType, requestParams, isBlacklisted }; if (isBlacklisted) { this._infoLogger({ rfqtMakerInteraction: { ...partialLogEntry } }); } else if (this._makerSupportsPair(url, makerAssetData, takerAssetData)) { const timeBeforeAwait = Date.now(); const maxResponseTimeMs = options.makerEndpointMaxResponseTimeMs === undefined ? constants.DEFAULT_RFQT_REQUEST_OPTS.makerEndpointMaxResponseTimeMs! : options.makerEndpointMaxResponseTimeMs; try { const quotePath = (() => { switch (quoteType) { case 'firm': return 'quote'; case 'indicative': return 'price'; default: throw new Error(`Unexpected quote type ${quoteType}`); } })(); const response = await quoteRequestorHttpClient.get<ResponseT>(`${url}/${quotePath}`, { headers: { '0x-api-key': options.apiKey }, params: requestParams, timeout: maxResponseTimeMs, }); const latencyMs = Date.now() - timeBeforeAwait; this._infoLogger({ rfqtMakerInteraction: { ...partialLogEntry, response: { included: true, apiKey: options.apiKey, takerAddress: requestParams.takerAddress, statusCode: response.status, latencyMs, }, }, }); rfqMakerBlacklist.logTimeoutOrLackThereof(url, latencyMs >= maxResponseTimeMs); result.push({ response: response.data, makerUri: url }); } catch (err) { const latencyMs = Date.now() - timeBeforeAwait; this._infoLogger({ rfqtMakerInteraction: { ...partialLogEntry, response: { included: false, apiKey: options.apiKey, takerAddress: requestParams.takerAddress, statusCode: err.response ? err.response.status : undefined, latencyMs, }, }, }); rfqMakerBlacklist.logTimeoutOrLackThereof(url, latencyMs >= maxResponseTimeMs); this._warningLogger( convertIfAxiosError(err), `Failed to get RFQ-T ${quoteType} quote from market maker endpoint ${url} for API key ${ options.apiKey } for taker address ${options.takerAddress}`, ); } } }), ); return result; } }
the_stack
import { PeerSource } from './PeerSource'; import { PeeringAgentBase } from './PeeringAgentBase'; import { SecureNetworkAgent, SecureNetworkEventType, ConnectionIdentityAuthEvent, IdentityLocation, IdentityAuthStatus, SecureMessageReceivedEvent } from '../network/SecureNetworkAgent'; import { Agent, AgentId } from '../../service/Agent'; import { NetworkAgent, Endpoint, ConnectionId, NetworkEventType, RemoteAddressListeningEvent, ConnectionStatusChangeEvent, ConnectionStatus, MessageReceivedEvent } from '../network/NetworkAgent'; import { AgentPod, Event } from '../../service/AgentPod'; import { LinkupAddress } from 'net/linkup/LinkupAddress'; import { Hash } from 'data/model'; import { Identity } from 'data/identity'; import { Logger, LogLevel } from 'util/logging'; type PeerInfo = { endpoint: Endpoint, identityHash: Hash, identity?: Identity }; type PeerConnection = { connId: ConnectionId; peer: PeerInfo, status: PeerConnectionStatus, timestamp: number }; enum PeerConnectionStatus { Connecting = 'connecting', ReceivingConnection = 'receiving-connection', WaitingForOffer = 'waiting-for-offer', OfferSent = 'offer-sent', OfferAccepted = 'offer-accepted', Ready = 'ready' }; // messages using during negotiation, before a connection has been secured: // (i.e. both parties have proved they have the right identity for this peer group) enum PeerMeshAgentMessageType  { PeeringOffer = 'peering-offer', PeeringOfferReply = 'peering-offer-reply', } type PeeringOfferMessage = { type: PeerMeshAgentMessageType.PeeringOffer, content: { peerGroupId: string, localIdentityHash: Hash } }; type PeeringOfferReplyMessage = { type: PeerMeshAgentMessageType.PeeringOfferReply, content: { peerGroupId: string, accepted: boolean, localIdentityHash: Hash } }; type PeerMeshAgentMessage = PeeringOfferMessage | PeeringOfferReplyMessage; // secured connection: enum SecureMessageTypes { PeerMessage = 'peer-message', ChooseConnection = 'choose-connection', ConfirmChosenConnection = 'confirm-chosen-connection' } type PeerMessage = { type: SecureMessageTypes.PeerMessage, peerGroupId: string, agentId: AgentId, content: any } // Sometimes two peers may end up with more than one connection established between them, // these messages are used to agree on a connection to use and safely close the others. type ConnectionSelectionMessage = { type: SecureMessageTypes.ChooseConnection | SecureMessageTypes.ConfirmChosenConnection, peerGroupId: string } type SecureMessage = PeerMessage | ConnectionSelectionMessage; enum PeerMeshEventType { NewPeer = 'new-peer', LostPeer = 'lost-peer' } type NewPeerEvent = { type: PeerMeshEventType.NewPeer, content: { peerGroupId: string, peer: PeerInfo } } type LostPeerEvent = { type: PeerMeshEventType.LostPeer, content: { peerGroupId: string, peer: PeerInfo } } type Params = { minPeers: number, maxPeers: number, peerConnectionTimeout: number, peerConnectionAttemptInterval: number tickInterval: number }; type CumulativeStats = { connectionInit: number; connectionAccpt: number; connectionTimeouts: number; } type Stats = { peers: number; connections: number; connectionsPerStatus: Map<PeerConnectionStatus, number>; } class PeerGroupAgent implements Agent { static controlLog = new Logger(PeerGroupAgent.name, LogLevel.INFO); static peersLog = new Logger(PeerGroupAgent.name, LogLevel.INFO); peerGroupId: string; localPeer: PeerInfo; peerSource: PeerSource; connections: Map<ConnectionId, PeerConnection>; connectionsPerEndpoint: Map<Endpoint, Array<ConnectionId>>; connectionAttemptTimestamps: Map<Endpoint, number>; onlineQueryTimestamps: Map<Endpoint, number>; chosenForDeduplication: Map<Endpoint, ConnectionId>; pod?: AgentPod; params: Params; tick: () => Promise<void>; tickTimerRef: any; stats: CumulativeStats; controlLog = PeerGroupAgent.controlLog; constructor(peerGroupId: string, localPeer: PeerInfo, peerSource: PeerSource, params?: Partial<Params>) { this.peerGroupId = peerGroupId; this.localPeer = localPeer; this.peerSource = peerSource; this.connections = new Map(); this.connectionsPerEndpoint = new Map(); this.connectionAttemptTimestamps = new Map(); this.onlineQueryTimestamps = new Map(); this.chosenForDeduplication = new Map(); if (params === undefined) { params = { }; } this.params = { minPeers: params.minPeers || 6, maxPeers: params.maxPeers || 12, peerConnectionTimeout: params.peerConnectionTimeout || 20, peerConnectionAttemptInterval: params.peerConnectionAttemptInterval || 20, tickInterval: params.tickInterval || 5 }; this.tick = async () => { this.cleanUp(); this.queryForOnlinePeers(); this.deduplicateConnections(); }; this.stats = { connectionInit: 0, connectionAccpt: 0, connectionTimeouts: 0 }; } getAgentId(): string { return PeerGroupAgent.agentIdForPeerGroup(this.peerGroupId); } getTopic(): string { return this.peerGroupId; } getLocalPeer(): PeerInfo { return this.localPeer; } ready(pod: AgentPod): void { this.controlLog.debug('Started PeerControlAgent on local ' + this.localPeer.endpoint + ' (id=' + this.localPeer.identityHash + ') for peerGroupId ' + this.peerGroupId); this.pod = pod; this.init(); } private async init() { const networkAgent = this.getNetworkAgent(); networkAgent.listen(this.localPeer.endpoint); for(const ci of this.getNetworkAgent().getAllConnectionsInfo()) { if (ci.localEndpoint === this.localPeer.endpoint && this.getNetworkAgent().checkConnection(ci.connId)) { let peer = await this.peerSource.getPeerForEndpoint(ci.remoteEndpoint); if (this.shouldConnectToPeer(peer)) { this.getNetworkAgent().acceptConnection(ci.connId, this.getAgentId()); let pc = this.addPeerConnection(ci.connId, peer as PeerInfo, PeerConnectionStatus.OfferSent); this.sendOffer(pc); } } } this.queryForOnlinePeers(); this.tickTimerRef = setInterval(this.tick, this.params.tickInterval * 1000); } getPeers() : Array<PeerInfo> { let seen = new Set<Endpoint>(); let unique = new Array<PeerInfo>(); for (const pc of this.connections.values()) { if (pc.status === PeerConnectionStatus.Ready && !seen.has(pc.peer.endpoint)) { unique.push(pc.peer); seen.add(pc.peer.endpoint); } } return unique; } validateConnectedPeer(ep: Endpoint) : boolean { let connId = this.findWorkingConnectionId(ep); return connId !== undefined; } // Peer messaging functions, to be used by other local agents: sendToAllPeers(agentId: AgentId, content: any): number { let count=0; for (let ep of this.connectionsPerEndpoint.keys()) { if (this.sendToPeer(ep, agentId, content)) { count = count + 1; } } this.controlLog.trace(this.localPeer.endpoint + ' sending message to all (' + count + ') peers.'); return count; } sendToPeer(ep: Endpoint, agentId: AgentId, content: any): boolean { let connId = this.findWorkingConnectionId(ep); if (connId !== undefined) { try { let pc = this.connections.get(connId) as PeerConnection; let peerMsg: PeerMessage = { type: SecureMessageTypes.PeerMessage, peerGroupId: this.peerGroupId, agentId: agentId, content: content }; let secureConnAgent = this.getSecureConnAgent(); secureConnAgent.sendSecurely( connId, this.localPeer.identityHash, pc.peer.identityHash, this.getAgentId(), peerMsg ); this.controlLog.trace(this.localPeer.endpoint + ' sending peer message to ' + ep); return true; } catch (e) { this.controlLog.warning('Could not send message', e); return false; } } else { this.controlLog.trace(this.localPeer.endpoint + ' could not send peer message to ' + ep); return false; } } peerSendBufferIsEmpty(ep: Endpoint): boolean { let connId = this.findWorkingConnectionId(ep); if (connId !== undefined) { return this.getNetworkAgent().connectionSendBufferIsEmpty(connId); } else { return false; } } getStats() : Stats { let stats: Stats = { peers: 0, connections: this.connections.size, connectionsPerStatus: new Map() }; for (const ep of this.connectionsPerEndpoint.keys()) { if (this.findWorkingConnectionId(ep) !== undefined) { stats.peers += 1; } } for (const conn of this.connections.values()) { let c = stats.connectionsPerStatus.get(conn.status); if (c === undefined) { c = 0; } stats.connectionsPerStatus.set(conn.status, c + 1); } return stats; } // Clean-up & new connection starting functions, called from the periodic tick private cleanUp() { let now = Date.now(); // Remove connections that: // 1. are ready, but the connection has been lost // 2. are not ready, and the connection timeout has elapsed for (const pc of Array.from(this.connections.values())) { if (pc.status === PeerConnectionStatus.Ready) { if (!this.getNetworkAgent().checkConnection(pc.connId)) { this.removePeerConnection(pc.connId); } } else { if (now > pc.timestamp + this.params.peerConnectionTimeout * 1000) { this.stats.connectionTimeouts += 1; this.removePeerConnection(pc.connId); } } } // Remove connection attempt timestamps that are too old to make a difference. // (i.e. peerConnectionAttemptInterval has already elapsed and we can try to reconnect) for (const [endpoint, timestamp] of Array.from(this.connectionAttemptTimestamps.entries())) { if (now > timestamp + this.params.peerConnectionAttemptInterval * 1000) { this.connectionAttemptTimestamps.delete(endpoint); } }; } private async queryForOnlinePeers() { PeerGroupAgent.peersLog.trace("Considering querying for peers on " + this.peerGroupId); if (this.connectionsPerEndpoint.size < this.params.minPeers) { let candidates = await this.peerSource.getPeers(this.params.minPeers * 5); let endpoints = new Array<Endpoint>(); let fallbackEndpoints = new Array<Endpoint>(); const now = Date.now(); PeerGroupAgent.peersLog.debug('Looking for peers, got ' + candidates.length + ' candidates'); for (const candidate of candidates) { if (this.localPeer.endpoint === candidate.endpoint) { continue; } if (this.connectionsPerEndpoint.get(candidate.endpoint) !== undefined) { continue; } const lastQueryTimestamp = this.onlineQueryTimestamps.get(candidate.endpoint); if (lastQueryTimestamp !== undefined && now < lastQueryTimestamp + this.params.peerConnectionAttemptInterval * 1000) { continue; } const lastAttemptTimestamp = this.connectionAttemptTimestamps.get(candidate.endpoint); if (fallbackEndpoints.length < this.params.minPeers - this.connectionsPerEndpoint.size) { fallbackEndpoints.push(candidate.endpoint); } if (lastAttemptTimestamp !== undefined && now < lastAttemptTimestamp + this.params.peerConnectionAttemptInterval * 1000) { continue } // we haven't queried nor attempted to connect to this endpoint recently, // and we are not connected / connecting now, so query: endpoints.push(candidate.endpoint); if (endpoints.length >= this.params.minPeers - this.connectionsPerEndpoint.size) { break; } } if (endpoints.length < this.params.minPeers) { endpoints = fallbackEndpoints; } for (const endpoint of endpoints) { this.onlineQueryTimestamps.set(endpoint, now); } if (endpoints.length > 0) { PeerGroupAgent.peersLog.debug('Querying for online endpoints: ' + endpoints); this.getNetworkAgent().queryForListeningAddresses( LinkupAddress.fromURL(this.localPeer.endpoint), endpoints.map((ep: Endpoint) => LinkupAddress.fromURL(ep))); } } else { PeerGroupAgent.peersLog.trace('Skipping querying for peers on ' + this.peerGroupId); } } // Connection deduplication logic. private deduplicateConnections() { for (const [endpoint, connIds] of this.connectionsPerEndpoint.entries()) { if (connIds.length > 1) { // Check if there was a chosen connection. let chosenConnId = this.chosenForDeduplication.get(endpoint); // And in that case, if it is still working. if (chosenConnId !== undefined && !this.getNetworkAgent().checkConnection(chosenConnId)) { chosenConnId = undefined; this.chosenForDeduplication.delete(endpoint); } if (chosenConnId === undefined) { let ready = []; for (const connId of connIds) { let pc = this.connections.get(connId); if (pc !== undefined && pc.status === PeerConnectionStatus.Ready && this.getNetworkAgent().checkConnection(connId)) { ready.push(connId); } } if (ready.length > 1) { PeerGroupAgent.controlLog.trace('Connection duplication detecetd (' + ready.length + ') to ' + endpoint); ready.sort(); chosenConnId = ready[0]; this.chosenForDeduplication.set(endpoint, chosenConnId); this.sendChosenConnection(chosenConnId); } } } } } shutdown() { if (this.tickTimerRef !== undefined) { clearInterval(this.tickTimerRef); this.tickTimerRef = undefined; } } // Deduplication messages. private sendChosenConnection(chosenConnId: ConnectionId) { this.sendConnectionSelectionMessage(chosenConnId, SecureMessageTypes.ChooseConnection); } private sendChosenConnectionConfirmation(chosenConnId: ConnectionId) { this.sendConnectionSelectionMessage(chosenConnId, SecureMessageTypes.ConfirmChosenConnection); } private sendConnectionSelectionMessage(chosenConnId: ConnectionId, type: (SecureMessageTypes.ChooseConnection | SecureMessageTypes.ConfirmChosenConnection)) { let connSelectionMsg: ConnectionSelectionMessage = { type: type, peerGroupId: this.peerGroupId, }; let pc = this.connections.get(chosenConnId) as PeerConnection; let secureConnAgent = this.getSecureConnAgent(); secureConnAgent.sendSecurely( chosenConnId, this.localPeer.identityHash, pc.peer.identityHash, this.getAgentId(), connSelectionMsg ); } // Actual deduplication, when peers have agreed on which connection to keep. private chooseConnection(chosenConnId: ConnectionId) { let pc = this.connections.get(chosenConnId) as PeerConnection; let allConnIds = this.connectionsPerEndpoint.get(pc.peer.endpoint); if (allConnIds !== undefined) { for (const connId of allConnIds) { if (connId !== chosenConnId) { PeerGroupAgent.controlLog.debug(() => 'Closing connection due to deduplication: ' + connId + ' (the chosen one is ' + chosenConnId + ')'); this.getNetworkAgent().releaseConnection(connId, this.getAgentId()); this.removePeerConnection(connId); } } } } // Connection handling: find a working connecton to an ep, decide whether to connect to or accept a // connection from a potential peer. private findWorkingConnectionId(ep: Endpoint) : ConnectionId | undefined { let connIds = this.connectionsPerEndpoint.get(ep); if (connIds !== undefined) { for (let connId of connIds) { let pc = this.connections.get(connId); if (pc !== undefined && pc.status === PeerConnectionStatus.Ready && this.getNetworkAgent().checkConnection(connId)) { return connId; } } } return undefined; // no luck } // Returns a peer corresponding to ep if we should connect, undefined otherwse. private shouldConnectToPeer(p?: PeerInfo) : boolean { if (p !== undefined && // - p is a peer this.connectionsPerEndpoint.size < this.params.minPeers && // - we're below minimum peers this.connectionsPerEndpoint.get(p.endpoint) === undefined && // - we're not connect[ed/ing] to ep this.localPeer.endpoint !== p.endpoint) { // - ep is not us // ====> then init conn. to ep const lastAttemptTimestamp = this.connectionAttemptTimestamps.get(p.endpoint); const now = Date.now(); // check if we have to wait because we've attempted to connect to ep recently. if (lastAttemptTimestamp === undefined ||  now > lastAttemptTimestamp + this.params.peerConnectionAttemptInterval * 1000) { // OK just do it. return true; } else { PeerGroupAgent.controlLog.trace('Will not connect, there is a recent connection attempt to the same endpoint.'); } } else { PeerGroupAgent.controlLog.trace( () => 'will not connect, resons: ' + '\np!==undefined => ' + (p !== undefined) + '\nthis.connectionsPerEndpoint.size < this.params.minPeers => ' + (this.connectionsPerEndpoint.size < this.params.minPeers) + '\nthis.connectionsPerEndpoint.get(p.endpoint) === undefined => ' + (p !== undefined && this.connectionsPerEndpoint.get(p.endpoint) === undefined) + '\nthis.localPeer.endpoint !== p.endpoint => ' + (p !== undefined && this.localPeer.endpoint !== p.endpoint)); } // if conditions above are not met, don't connect. return false; } // Returns a peer corresponding to ep if we should accept the connection, undefined otherwise private async shouldAcceptPeerConnection(p?: PeerInfo) { if (p===undefined) { return false; } else { const conns = this.connectionsPerEndpoint.get(p.endpoint); const alreadyConnected = conns !== undefined && conns.length > 0; return (this.connectionsPerEndpoint.size + (alreadyConnected? 0 : 1) <= this.params.maxPeers && // - we're below maximum peers this.findWorkingConnectionId(p.endpoint) === undefined && // - there's not a working conn to ep this.localPeer.endpoint !== p.endpoint); // - ep is not us); } } // Connection metadata: create / destroy a new PeerConnection private addPeerConnection(connId: ConnectionId, peer: PeerInfo, status: PeerConnectionStatus) { if (this.connections.get(connId) !== undefined) { PeerGroupAgent.controlLog.warning(() => 'Trying to add connection ' + connId + ', but it already exists.') throw new Error('Trying to add connection ' + connId + ', but it already exists.'); } let pc: PeerConnection = { connId: connId, peer: peer, status: status, timestamp: Date.now() }; this.connections.set(connId, pc); let conns = this.connectionsPerEndpoint.get(peer.endpoint); if (conns === undefined) { conns = []; this.connectionsPerEndpoint.set(peer.endpoint, conns); } conns.unshift(connId); return pc; } private removePeerConnection(connId: ConnectionId) { let pc = this.connections.get(connId); if (pc !== undefined) { this.connections.delete(connId); let conns = this.connectionsPerEndpoint.get(pc.peer.endpoint); if (conns !== undefined) { let idx = conns.indexOf(connId); if (idx >= 0) { conns.splice(idx, 1); } if (conns.length === 0) { this.connectionsPerEndpoint.delete(pc.peer.endpoint); conns = undefined; } } if (pc.status === PeerConnectionStatus.Ready && conns === undefined ) { this.broadcastLostPeerEvent(pc.peer); } } } // Ask SecureConnectionAgent to secure a connection, given local and remote identities private secureConnection(pc: PeerConnection) { const secureConnAgent = this.getSecureConnAgent(); secureConnAgent.secureForReceiving(pc.connId, this.localPeer.identity as Identity); secureConnAgent.secureForSending(pc.connId, pc.peer.identityHash, pc.peer.identity); } private checkSecuredConnection(pc: PeerConnection) { const secureConnAgent = this.getSecureConnAgent(); let localId = secureConnAgent.getLocalVerifiedIdentity(pc.connId, this.localPeer.identityHash); let remoteId = secureConnAgent.getRemoteVerifiedIdentity(pc.connId, pc.peer.identityHash); let success = (localId !== undefined && remoteId !== undefined); pc.peer.identity = remoteId; return success; } // handling of events for peer connection negotiation: private async onOnlineEndpointDiscovery(ep: Endpoint) { this.controlLog.debug(() => (this.localPeer.endpoint + ' has discovered that ' + ep + ' is online.')); let peer = await this.peerSource.getPeerForEndpoint(ep); if (this.shouldConnectToPeer(peer)) { this.controlLog.debug(() => (this.localPeer.endpoint + ' will initiate peer connection to ' + ep + '.')); let connId = this.getNetworkAgent().connect(this.localPeer.endpoint, (peer as PeerInfo).endpoint, this.getAgentId()); this.addPeerConnection(connId, peer as PeerInfo, PeerConnectionStatus.Connecting); this.connectionAttemptTimestamps.set(ep, Date.now()); this.stats.connectionInit += 1; } else { this.controlLog.debug(() => (this.localPeer.endpoint + ' will NOT initiate peer connection to ' + ep + '.')); } } private async onConnectionRequest(connId: ConnectionId, local: Endpoint, remote: Endpoint) { if (this.localPeer.endpoint === local) { let peer = await this.peerSource.getPeerForEndpoint(remote); this.controlLog.trace(this.localPeer.endpoint + ' is receiving a conn. request from ' + remote + ', connId is ' + connId); if (await this.shouldAcceptPeerConnection(peer)) { this.controlLog.debug('Will accept requested connection ' + connId + '!'); this.addPeerConnection(connId, peer as PeerInfo, PeerConnectionStatus.ReceivingConnection); this.getNetworkAgent().acceptConnection(connId, this.getAgentId()); this.stats.connectionAccpt += 1; } } } private onConnectionEstablishment(connId: ConnectionId, local: Endpoint, remote: Endpoint) { let pc = this.connections.get(connId); this.controlLog.trace(() => this.localPeer.endpoint + ' is receiving a connection from ' + remote + ' connId is ' + connId); if (pc !== undefined && this.localPeer.endpoint === local && pc.peer.endpoint === remote) { if (pc.status === PeerConnectionStatus.Connecting) { this.sendOffer(pc); pc.status = PeerConnectionStatus.OfferSent; } else if (pc.status === PeerConnectionStatus.ReceivingConnection) { pc.status = PeerConnectionStatus.WaitingForOffer; } } else { this.controlLog.trace(() => 'Unknown connection ' + connId + ', ignoring. pc=' + pc + ' local=' + local + ' remote='+ remote); } } private async onReceivingOffer(connId: ConnectionId, source: Endpoint, destination: Endpoint, peerGroupId: string, remoteIdentityHash: Hash) { this.controlLog.trace(() => (this.localPeer.endpoint + ' is receiving peering offer from ' + source)); // do this here so we get atomicity below. let peer = await this.peerSource.getPeerForEndpoint(source); let reply = false; let accept = false; let pc = this.connections.get(connId); // Maybe the PeerControlAgent, upong starting in another node, found an existint connection // to us, and wants to start a PeerConnection over it. So we have no previous state referring // to connection establishment, and we just receive the offer over an existing one. if (pc === undefined) { this.controlLog.trace('Found no previous state'); if (await this.shouldAcceptPeerConnection(peer)) { this.controlLog.debug('Will accept offer ' + connId + '!'); // Act as if we had just received the connection, process offer below. this.addPeerConnection(connId, peer as PeerInfo, PeerConnectionStatus.WaitingForOffer); accept = true; reply = true; } else { this.controlLog.debug('Will NOT accept offer ' + connId + '!'); if (peer !== undefined && peer.identityHash === remoteIdentityHash && this.peerGroupId === peerGroupId) { // OK, we don't want to accept, but this is, in principle, a valid peer. // Send a rejection below. accept = false; reply = true; } } } else { // pc !== undefined // OK, we had previous state - if everything checks up, accept. this.controlLog.trace('Found previous state:' + pc.status); if (peerGroupId === this.peerGroupId && pc.status === PeerConnectionStatus.WaitingForOffer && source === pc.peer.endpoint && destination === this.localPeer.endpoint && remoteIdentityHash === pc.peer.identityHash) { this.controlLog.trace('Everything checks out!'); reply = true; accept = true; } else { this.controlLog.trace('The request is invalid.'); } } // If the offer was correct, we send a reply. // Notice: accept implies reply. if (reply) { this.sendOfferReply(connId, accept); } // Act upon the offer: if it was accepted, update local state and // initiate connection authentication. Otherwise // clear the state on this connection. if (accept) { const apc = pc as PeerConnection; if (!this.checkSecuredConnection(apc)) { apc.status = PeerConnectionStatus.OfferAccepted; this.secureConnection(apc); } else { apc.status = PeerConnectionStatus.Ready; this.broadcastNewPeerEvent(apc.peer); } } else { PeerGroupAgent.controlLog.debug('Dropping connection ' + connId + ': offer was rejected'); this.removePeerConnection(connId); this.getNetworkAgent().releaseConnectionIfExists(connId, this.getAgentId()); } } private onReceivingOfferReply(connId: ConnectionId, source: Endpoint, destination: Endpoint, peerGroupId: string, remoteIdentityHash: Hash, accepted: boolean) { let pc = this.connections.get(connId); this.controlLog.trace(this.localPeer.endpoint + ' is receiving offer reply from ' + source); if (pc !== undefined && peerGroupId === this.peerGroupId && pc.status === PeerConnectionStatus.OfferSent && source === pc.peer.endpoint && destination === this.localPeer.endpoint && remoteIdentityHash === pc.peer.identityHash && accepted) { if (!this.checkSecuredConnection(pc)) { pc.status = PeerConnectionStatus.OfferAccepted; this.secureConnection(pc); } else { pc.status = PeerConnectionStatus.Ready; this.broadcastNewPeerEvent(pc.peer); } } } private onConnectionAuthentication(connId: ConnectionId, identityHash: Hash, identity: Identity, identityLocation: IdentityLocation) { let pc = this.connections.get(connId); identityHash; identity; identityLocation; if (pc !== undefined && pc.status === PeerConnectionStatus.OfferAccepted) { if (this.checkSecuredConnection(pc)) { pc.status = PeerConnectionStatus.Ready; this.broadcastNewPeerEvent(pc.peer); } } } private onConnectionClose(connId: ConnectionId) { this.removePeerConnection(connId); } // Offer / offer reply message construction, sending. private sendOffer(pc: PeerConnection) { let message: PeeringOfferMessage = { type: PeerMeshAgentMessageType.PeeringOffer, content: { peerGroupId: this.peerGroupId, localIdentityHash: this.localPeer.identityHash } }; this.controlLog.trace(() => (this.localPeer.endpoint + ' sending peering offer to ' + pc.peer.endpoint)); this.getNetworkAgent().sendMessage(pc.connId, this.getAgentId(), message); } private sendOfferReply(connId: ConnectionId, accept: boolean) { let message: PeeringOfferReplyMessage = { type: PeerMeshAgentMessageType.PeeringOfferReply, content: { peerGroupId: this.peerGroupId, localIdentityHash: this.localPeer.identityHash, accepted: accept } }; this.controlLog.trace(() => (this.localPeer.endpoint + ' sending peering offer reply to ' + this.connections.get(connId)?.peer.endpoint) + ': ' + (accept? 'ACCEPT' : 'REJECT')); this.getNetworkAgent().sendMessage(connId, this.getAgentId(), message); } // handle peer message reception private onPeerMessage(connId: ConnectionId, sender: Hash, recipient: Hash, peerGroupId: string, agentId: AgentId, message: any) { let pc = this.connections.get(connId); if (peerGroupId === this.peerGroupId && pc !== undefined && pc.status === PeerConnectionStatus.Ready && pc.peer.identityHash === sender && this.localPeer.identityHash === recipient) { let agent = this.getLocalAgent(agentId); if (agent !== undefined && agent instanceof PeeringAgentBase) { let peeringAgent = agent as PeeringAgentBase; peeringAgent.receivePeerMessage(pc.peer.endpoint, sender, recipient, message); } } } // If two peers attempt to connect to each other nearly at the same time, they may end up with // two different connections between a single pair of endpoints. The following exchange allows // them to agree on a connection to use, and safely close the rest. private onConnectionSelection(connId: ConnectionId, sender: Hash, recipient: Hash, type: (SecureMessageTypes.ChooseConnection | SecureMessageTypes.ConfirmChosenConnection), peerGroupId: string) { connId; sender; recipient; type; peerGroupId; PeerGroupAgent.controlLog.trace('Connection selection for ' + connId + ' sender=' + sender + ', recipient=' + recipient + ', type=' + type); let pc = this.connections.get(connId); // If connId represents an acceptable option (a working connection in Ready state): if (pc !== undefined && pc.status === PeerConnectionStatus.Ready && this.getNetworkAgent().checkConnection(connId)) { let accept = false; let chosenConnId = this.chosenForDeduplication.get(pc.peer.endpoint); // if we didn't propose another connecitons, choose this one. if (chosenConnId === undefined || chosenConnId === connId) { accept = true; } else { const options = new Array<ConnectionId>(); options.push(connId); options.push(chosenConnId); options.sort(); const tieBreak = options[0]; accept = tieBreak === connId; } if (accept) { this.chooseConnection(connId); if (type === SecureMessageTypes.ChooseConnection) { this.sendChosenConnectionConfirmation(connId); } } } } /* The functions,receiveLocalEvent receives events generated by the other agents in the pod * and fires the appropriate event handlers defined above (onConnectionRequest, onReceivingOffer, * etc.) */ receiveLocalEvent(ev: Event): void { if (ev.type === NetworkEventType.RemoteAddressListening) { const listenEv = ev as RemoteAddressListeningEvent; this.onOnlineEndpointDiscovery(listenEv.content.remoteEndpoint); } else if (ev.type === NetworkEventType.ConnectionStatusChange) { const connEv = ev as ConnectionStatusChangeEvent; if (connEv.content.status === ConnectionStatus.Closed) { this.onConnectionClose(connEv.content.connId); } else if (connEv.content.status === ConnectionStatus.Received) { this.onConnectionRequest(connEv.content.connId, connEv.content.localEndpoint, connEv.content.remoteEndpoint); } else if (connEv.content.status === ConnectionStatus.Ready) { this.onConnectionEstablishment(connEv.content.connId, connEv.content.localEndpoint, connEv.content.remoteEndpoint); } } else if (ev.type === SecureNetworkEventType.ConnectionIdentityAuth) { let connAuth = ev as ConnectionIdentityAuthEvent; if (connAuth.content.status === IdentityAuthStatus.Accepted) { this.onConnectionAuthentication(connAuth.content.connId, connAuth.content.identityHash, connAuth.content.identity as Identity, connAuth.content.identityLocation); } } else if (ev.type === SecureNetworkEventType.SecureMessageReceived) { // The SecureConnectionAgent relies secure messages destined to this agent through local events. // Since this messages arrive through a secured connection, we know the sender is in possesion of // a given identity, and we know at which identity the message was directed (encrypted for). let secMsgEv = ev as SecureMessageReceivedEvent; let payload: SecureMessage = secMsgEv.content.payload; if (payload.type === SecureMessageTypes.PeerMessage) { this.onPeerMessage(secMsgEv.content.connId, secMsgEv.content.sender, secMsgEv.content.recipient, payload.peerGroupId, payload.agentId, payload.content); } else if (payload.type === SecureMessageTypes.ChooseConnection || payload.type === SecureMessageTypes.ConfirmChosenConnection) { this.onConnectionSelection(secMsgEv.content.connId, secMsgEv.content.sender, secMsgEv.content.recipient, payload.type, payload.peerGroupId); } } else if (ev.type === NetworkEventType.MessageReceived) { let msgEv = ev as MessageReceivedEvent; this.receiveMessage(msgEv.content.connectionId , msgEv.content.source, msgEv.content.destination, msgEv.content.content); } } receiveMessage(connId: ConnectionId, source: Endpoint, destination: Endpoint, content: any): void { let message = content as PeerMeshAgentMessage; if (message.type === PeerMeshAgentMessageType.PeeringOffer) { let offer = (content as PeeringOfferMessage).content; this.onReceivingOffer(connId, source, destination, offer.peerGroupId, offer.localIdentityHash); } else if (message.type === PeerMeshAgentMessageType.PeeringOfferReply) { let offerReply = (content as PeeringOfferReplyMessage).content; this.onReceivingOfferReply(connId, source, destination, offerReply.peerGroupId, offerReply.localIdentityHash, offerReply.accepted); } } // emitted events private broadcastNewPeerEvent(peer: PeerInfo) { PeerGroupAgent.controlLog.debug(() => this.localPeer.endpoint + ' hasa new peer: ' + peer.endpoint); let ev: NewPeerEvent = { type: PeerMeshEventType.NewPeer, content: { peerGroupId: this.peerGroupId, peer: peer } }; this.pod?.broadcastEvent(ev); } private broadcastLostPeerEvent(peer: PeerInfo) { PeerGroupAgent.controlLog.debug(() => this.localPeer.endpoint + ' hasa lost a peer: ' + peer.endpoint); let ev: LostPeerEvent = { type: PeerMeshEventType.LostPeer, content: { peerGroupId: this.peerGroupId, peer: peer } }; this.pod?.broadcastEvent(ev); } // shorthand functions private getNetworkAgent() { return this.pod?.getAgent(NetworkAgent.AgentId) as NetworkAgent; } private getLocalAgent(agentId: AgentId) { return this.pod?.getAgent(agentId) as Agent; } private getSecureConnAgent() { return this.getLocalAgent(SecureNetworkAgent.Id) as SecureNetworkAgent; } static agentIdForPeerGroup(peerGroupId: string) { return 'peer-control-for-' + peerGroupId; } } type Config = Partial<Params>; export { PeerGroupAgent, PeerInfo, PeerMeshEventType, NewPeerEvent, LostPeerEvent, Config as PeerGroupAgentConfig };
the_stack
import { assert } from "chai"; import { skip, suite, test } from "mocha-typescript"; import * as path from "path"; import { CompletionItemKind, CompletionRequest, DefinitionRequest, DiagnosticSeverity, DidOpenTextDocumentNotification, DidOpenTextDocumentParams, DidSaveTextDocumentNotification, DidSaveTextDocumentParams, DocumentLinkParams, DocumentLinkRequest, IConnection, TextDocument, TextDocumentPositionParams, TextDocuments, createConnection } from "vscode-languageserver"; import { URI } from "vscode-uri"; import { Server } from "../Server"; import { transformPathsFromUri } from "../util/pathTransformer"; import { createTextDocumentMock } from "./util/createTextDocumentMock"; import { createTextDocumentsMock } from "./util/createTextDocumentsMock"; import { TestStream } from "./util/TestStream"; const TEST_DIR = path.resolve(__dirname, "..", "..", "src", "test"); const pathToUri = (relativePath: string) => URI.file(path.resolve(TEST_DIR, relativePath)).toString(); const EMBER_CLASSIC_TEMPLATE_A_URI = pathToUri("fixtures/ember-classic/templates/components/a.hbs"); const EMBER_CLASSIC_BLOCK_A_URI = pathToUri("fixtures/ember-classic/styles/components/a.block.css"); @suite("Language Server | Server | tags: ember-classic, language-server") export class LanguageServerServerTest { mockServerConnection: IConnection; mockClientConnection: IConnection; documents: TextDocuments; constructor() { const input = new TestStream(); const output = new TestStream(); this.mockServerConnection = createConnection(input, output); this.mockClientConnection = createConnection(output, input); this.mockClientConnection.listen(); const textDocumentsByUri = new Map<string, TextDocument>(); textDocumentsByUri.set(EMBER_CLASSIC_TEMPLATE_A_URI, createTextDocumentMock(EMBER_CLASSIC_TEMPLATE_A_URI)); textDocumentsByUri.set(EMBER_CLASSIC_BLOCK_A_URI, createTextDocumentMock(EMBER_CLASSIC_BLOCK_A_URI)); this.documents = createTextDocumentsMock(textDocumentsByUri); } private startServer() { const server = new Server(this.mockServerConnection, this.documents); server.listen(); return server; } @test async "it returns the expected definitions for local block"() { let server = this.startServer(); const params: TextDocumentPositionParams = { textDocument: { uri: EMBER_CLASSIC_TEMPLATE_A_URI, }, position: { line: 0, character: 17, }, }; const response = await this.mockClientConnection.sendRequest(DefinitionRequest.type, params); assert.deepEqual(response, { uri: transformPathsFromUri(EMBER_CLASSIC_TEMPLATE_A_URI, server.pathTransformer, server.config).blockUri || "", range: { start: { line: 6, character: 1 }, end: { line: 6, character: 1 }, }, }); } @test async "it returns the expected definitions for a class that is defined as part of a multiline string"() { let server = this.startServer(); const params: TextDocumentPositionParams = { textDocument: { uri: EMBER_CLASSIC_TEMPLATE_A_URI, }, position: { line: 3, character: 5, }, }; const response = await this.mockClientConnection.sendRequest(DefinitionRequest.type, params); assert.deepEqual(response, { uri: transformPathsFromUri(EMBER_CLASSIC_TEMPLATE_A_URI, server.pathTransformer, server.config).blockUri || "", range: { start: { line: 10, character: 1 }, end: { line: 10, character: 1 }, }, }); } @test async "it returns the expected definitions for a block reference"() { this.startServer(); const params: TextDocumentPositionParams = { textDocument: { uri: EMBER_CLASSIC_TEMPLATE_A_URI, }, position: { line: 1, character: 19, }, }; const response = await this.mockClientConnection.sendRequest(DefinitionRequest.type, params); assert.deepEqual(response, { uri: pathToUri("fixtures/ember-classic/styles/blocks/utils.block.css"), range: { start: { line: 4, character: 1 }, end: { line: 4, character: 1 }, }, }); } @test async "it returns no definitions when triggering go to definition on a class that has not been defined"() { this.startServer(); const params: TextDocumentPositionParams = { textDocument: { uri: EMBER_CLASSIC_TEMPLATE_A_URI, }, position: { line: 5, character: 17, }, }; const response = await this.mockClientConnection.sendRequest(DefinitionRequest.type, params); assert.deepEqual(response, []); } @test async "it returns the expected completions for local block"() { this.startServer(); const params: TextDocumentPositionParams = { textDocument: { uri: EMBER_CLASSIC_TEMPLATE_A_URI, }, position: { line: 0, character: 17, }, }; const response = await this.mockClientConnection.sendRequest(CompletionRequest.type, params); const expectedCompletionKind = CompletionItemKind.Property; assert.deepEqual(response, [{ label: "a-1", kind: expectedCompletionKind }, { label: "a-2", kind: expectedCompletionKind }, { label: "a-3", kind: expectedCompletionKind }]); } @test async "it returns the expected completions for a block reference"() { this.startServer(); const params: TextDocumentPositionParams = { textDocument: { uri: EMBER_CLASSIC_TEMPLATE_A_URI, }, position: { line: 1, character: 20, }, }; const response = await this.mockClientConnection.sendRequest(CompletionRequest.type, params); const expectedCompletionKind = CompletionItemKind.Property; assert.deepEqual(response, [{ label: "display-flex", kind: expectedCompletionKind }, { label: "display-block", kind: expectedCompletionKind }, ]); } @test async "it returns the expected template diagnostics for a class that is not defined when a file is opened"() { this.startServer(); const document = this.documents.get(EMBER_CLASSIC_TEMPLATE_A_URI)!; const params: DidOpenTextDocumentParams = { textDocument: { uri: EMBER_CLASSIC_TEMPLATE_A_URI, version: 1, text: document.getText(), languageId: "handlebars", }, }; this.mockClientConnection.sendNotification(DidOpenTextDocumentNotification.type, params); let publishParams = await new Promise((resolve) => { this.mockClientConnection.onNotification((method, params) => { if (method === "textDocument/publishDiagnostics") { if (params.diagnostics.length) { resolve(params); } } }); }); assert.deepEqual(publishParams, { uri: EMBER_CLASSIC_TEMPLATE_A_URI, diagnostics: [{ severity: DiagnosticSeverity.Error, range: { start: { line: 5, character: 17, }, end: { line: 5, character: 33, }, }, message: "Class name 'i-do-not-exist-1' not found.", }, { severity: DiagnosticSeverity.Error, range: { start: { line: 6, character: 26, }, end: { line: 6, character: 42, }, }, message: "Class name 'i-do-not-exist-2' not found.", }], }); } // TODO: figure out why the client does not receive the notification after // sending synthetic save event. This is pretty much covered by the properly // functioning "onDidOpen" test, and the "ondDidSave" event is reliably fired // under real working conditions. @skip async "it returns the expected template diagnostics when using a class that is not defined when a file is saved"() { this.startServer(); const document = this.documents.get(EMBER_CLASSIC_TEMPLATE_A_URI)!; const params: DidSaveTextDocumentParams = { textDocument: { uri: EMBER_CLASSIC_TEMPLATE_A_URI, version: 2, }, text: document.getText(), }; this.mockClientConnection.sendNotification(DidSaveTextDocumentNotification.type, params); let publishParams = await new Promise((resolve) => { this.mockClientConnection.onNotification((method, params) => { if (method === "textDocument/publishDiagnostics") { if (params.diagnostics.length) { resolve(params); } } }); }); assert.deepEqual(publishParams, { uri: EMBER_CLASSIC_TEMPLATE_A_URI, diagnostics: [{ severity: DiagnosticSeverity.Error, range: { start: { line: 0, character: 14, }, end: { line: 0, character: 32, }, }, message: 'No Style ".non-existent-class" found on Block "a".', }], }); } @test async "it returns the expected css block diagnostics when a block file is changed"() { const server = this.startServer(); const blockWithErrorsUri = pathToUri("fixtures/ember-classic/styles/blocks/block-with-errors.block.css"); await server.onDidChangeContent({ document: createTextDocumentMock(blockWithErrorsUri), }); let publishParams = await new Promise((resolve) => { this.mockClientConnection.onNotification((method, params) => { if (method === "textDocument/publishDiagnostics") { if (params.diagnostics.length) { resolve(params); } } }); }); assert.deepEqual(publishParams, { uri: blockWithErrorsUri, diagnostics: [{ severity: DiagnosticSeverity.Error, range: { start: { line: 4, character: 2, }, end: { line: 4, character: 4, }, }, message: "Two distinct classes cannot be selected on the same element: .a.b", }], }); } @test async "it returns the expected document links"() { this.startServer(); let params: DocumentLinkParams = { textDocument: { uri: pathToUri("fixtures/ember-classic/styles/components/a.block.css"), }, }; let response = await this.mockClientConnection.sendRequest(DocumentLinkRequest.type, params); assert.deepEqual(response, [{ range: { start: { character: 19, line: 0, }, end: { character: 44, line: 0, }, }, target: pathToUri("fixtures/ember-classic/styles/blocks/utils.block.css"), }]); } @test async "it returns the expected completions for a block/export path in a block file"() { const textDocumentsByUri = new Map<string, TextDocument>(); const importCompletionsFixtureUri = pathToUri("fixtures/ember-classic/styles/components/import-completions.block.css"); textDocumentsByUri.set(importCompletionsFixtureUri, createTextDocumentMock(importCompletionsFixtureUri)); this.documents = createTextDocumentsMock(textDocumentsByUri); this.startServer(); // directory completions const params1: TextDocumentPositionParams = { textDocument: { uri: importCompletionsFixtureUri, }, position: { line: 0, character: 27, }, }; const response1 = await this.mockClientConnection.sendRequest(CompletionRequest.type, params1); assert.deepEqual( response1, [ { kind: 19, label: "blocks", }, { kind: 19, label: "components", }, ], "it returns the expected folder completions"); // file name completions const params2: TextDocumentPositionParams = { textDocument: { uri: importCompletionsFixtureUri, }, position: { line: 1, character: 30, }, }; const response2 = await this.mockClientConnection.sendRequest(CompletionRequest.type, params2); assert.deepEqual( response2, [ { "kind": 17, "label": "block-with-errors.block.css", }, { "kind": 17, "label": "utils.block.css", }, ], "it returns the expected file completions"); // partially typed filename completion const params3: TextDocumentPositionParams = { textDocument: { uri: importCompletionsFixtureUri, }, position: { line: 2, character: 32, }, }; const response3 = await this.mockClientConnection.sendRequest(CompletionRequest.type, params3); assert.deepEqual( response3, [ { kind: 17, label: "block-with-errors.block.css", }, { kind: 17, label: "utils.block.css", }, ], "it returns the expected file completions"); // local directory reference const params4: TextDocumentPositionParams = { textDocument: { uri: importCompletionsFixtureUri, }, position: { line: 3, character: 23, }, }; const response4 = await this.mockClientConnection.sendRequest(CompletionRequest.type, params4); assert.deepEqual( response4, [ { kind: 17, label: "a.block.css", }, ], "it returns the expected file completions"); } }
the_stack
import { PageContent } from "../pageModel"; import { SENTINEL_CONTENT, MAX_BUFFER_LENGTH } from "../contentTree/tree"; import { SENTINEL_STRUCTURE } from "../structureTree/tree"; import { chunks, TokenType } from "tiny-html-lexer"; import { EMPTY_TREE_ROOT } from "../tree/tree"; import { KeyValueStr, TagType } from "../structureTree/structureModel"; import { InsertStructureProps } from "../structureTree/actions"; import he from "he"; import { insertStructureNode } from "../structureTree/insert"; import { insertContentDOM } from "../contentTree/insert.dom"; interface Attributes { [key: string]: string; } /** * Gets the attribute name for the given string. It strips out the `-`, and * makes it all lower-case, unless `isStyleProperty` is true, upon which it * transforms the string into camelCase. * * For example, with `isStyleProperty == false`: * - `hello-world` => `helloworld` * - `hello-World` => `helloworld` * * For example, with `isStyleProperty == true`: * - `hello-world` => `helloWorld` * @param name The name to get the new name for. * @param isStyleProperty If true, then gets the CSS-in-JS attribute name of a * key - i.e. kebab-case to camelCase. */ export function getAttributeName( name: string, isStyleProperty = false, ): string { const newName = name .split("-") .reduce((acc: string, curr: string): string => { if (isStyleProperty) { if (acc) { acc += curr[0].toUpperCase() + curr.slice(1); } else { acc = curr; } return acc; } else { return acc + curr; } }, ""); return newName; } /** * Given a string, it returns an object of key-value string pairs of the style, * with CSS-in-JS compatible keys. */ export function getStyle(text: string): KeyValueStr { return text .split(";") .reduce((acc: KeyValueStr, curr: string): KeyValueStr => { const [key, value] = curr.split(":"); acc[getAttributeName(key, true)] = value; return acc; }, {}); } /** * Parses HTML content, and returns a new `PageContent` instance containing * the parsed HTML. * @param content The HTML content to parse. */ export default function parse(content: string): PageContent { const page: PageContent = { buffers: [], content: { nodes: [SENTINEL_CONTENT], root: EMPTY_TREE_ROOT, }, previouslyInsertedContentNodeIndex: null, previouslyInsertedContentNodeOffset: null, structure: { nodes: [SENTINEL_STRUCTURE], root: EMPTY_TREE_ROOT, }, }; const stream = chunks(content); let lastTextNode: InsertStructureProps; let structureNodeOffset = 1; const markdownStack: string[][] = []; const charRef: Set<TokenType> = new Set([ "charRef-decimal", "charRef-hex", "charRef-named", ] as TokenType[]); const tags: KeyValueStr = { cite: "{!cite} ", h1: "# ", h2: "## ", h3: "### ", h4: "#### ", h5: "##### ", h6: "###### ", }; /** * Consume all the tokens until it reaches a token in `targetTypes`. * @param targetTypes The tokens which when reached, consumption of tokens * should end. The terminating token is returned. */ function consumeUpToType(...targetTypes: TokenType[]): TokenType { let [type] = stream.next().value; const target = new Set(targetTypes); while (!target.has(type)) { [type] = stream.next().value; } return type; } /** * Gets the next attribute value from the HTML. */ function getNextAttributeValue(): string { consumeUpToType("attribute-value-start"); const [, value] = stream.next().value; consumeUpToType("attribute-value-end"); return value; } /** * Gets all the attributes and their values, until it leaves the current tag. */ function getAttributes(): Attributes { const attributes: Attributes = {}; // eslint-disable-next-line no-constant-condition while (true) { const terminatingType = consumeUpToType( "space", "tag-end", "tag-end-autoclose", ); if (terminatingType === "space") { const [type, chunk] = stream.next().value; if (type === "tag-end" || type === "tag-end-autoclose") { return attributes; } attributes[chunk] = getNextAttributeValue(); } else { return attributes; } } } /** * Handles the start of a HTML tag. */ function html(): void { const attributes = getAttributes(); if (attributes.lang) { page.language = attributes.lang as string; } } /** * Handles the start of a title tag. */ function title(): void { consumeUpToType("tag-end"); const [type, chunk] = stream.next().value; if (type !== "rcdata") { throw new TypeError("Expected `rcdata` type."); } page.title = chunk; consumeUpToType("tag-end"); } /** * Handles the start of a meta tag. */ function meta(): void { const attributes = getAttributes(); if (attributes["http-equiv"] === "Content-Type" && attributes["content"]) { page.charset = (attributes["content"] as string).split("=")[1]; } else if (attributes["name"] === "created" && attributes["content"]) { page.created = attributes["content"] as string; } } /** * Handles the start of a body tag. */ function body(): void { const attributes = getAttributes(); if (attributes["data-absolute-enabled"]) { page.dataAbsoluteEnabled = Boolean(attributes["data-absolute-enabled"]); } if (attributes["style"]) { page.defaultStyle = getStyle(attributes["style"]); } } /** * Handles the start of a span tag. */ function span(): string { const style = getStyle(getAttributes().style); const markdown: string[] = []; if (style.fontWeight === "bold") { markdown.push("**"); } if (style.fontStyle === "italic") { markdown.push("_"); } if (style.textDecoration) { markdown.push(`{text-decoration:${style.textDecoration}}`); } if (style.backgroundColor) { markdown.push(`{background-color:${style.backgroundColor}}`); } if (style.color) { markdown.push(`{color:${style.color}}`); } markdownStack.push(markdown); return markdown.join(""); } /** * Handles the end of a span tag. */ function spanEnd(): string { consumeUpToType("tag-end"); const forwardsContent = markdownStack.pop()!; return forwardsContent.reduce((acc, curr): string => { return curr + acc; }, ""); } function textBody(tag: string): void { let [type, chunk] = stream.next().value; let content = ""; if (tags[tag]) { content += tags[tag]; } while (!(type === "endTag-start" && chunk.slice(2) === tag)) { if (type === "data") { content += chunk; } else if (charRef.has(type)) { const charRefContent = he.decode(chunk); content += charRefContent; } else if (type === "startTag-start") { switch (chunk) { case "<span": content += span(); break; case "<sub": content += "{!sub}"; break; case "<sup": content += "{!sup}"; break; default: break; } } else if (type === "endTag-start") { switch (chunk) { case "</span": content += spanEnd(); break; case "</sub": content += "{!sub}"; break; case "</sup": content += "{!sup}"; break; default: break; } } [type, chunk] = stream.next().value; } // lastTextNode.length = content.length; insertStructureNode(page, { ...lastTextNode, length: content.length, offset: structureNodeOffset, }); structureNodeOffset += 1; insertStructureNode(page, { id: lastTextNode.id, length: 0, offset: structureNodeOffset, tag: lastTextNode.tag, tagType: TagType.EndTag, }); structureNodeOffset += 1; const offset = page.content.nodes[page.content.nodes.length - 1].length; insertContentDOM( page, { content, end: { nodeIndex: 1, nodeLocalOffset: offset, }, localOffset: offset, start: { nodeIndex: 1, nodeLocalOffset: 0, }, structureNodeIndex: page.structure.nodes.length - (page.structure.nodes[page.structure.nodes.length - 1].tagType !== TagType.EndTag ? 1 : 2), }, MAX_BUFFER_LENGTH, ); consumeUpToType("tag-end"); } function text(tag: keyof HTMLElementTagNameMap): void { const { id, style: styleStr, ...attributes } = getAttributes(); lastTextNode = { id, length: 0, offset: 0, tag, tagType: TagType.StartTag, }; if (styleStr) { lastTextNode.style = getStyle(styleStr); } if (Object.keys(attributes).length > 0) { const renamedKeyAttributes: KeyValueStr = {}; for (const key in attributes) { renamedKeyAttributes[getAttributeName(key)] = attributes[key]; } lastTextNode.attributes = renamedKeyAttributes; } textBody(tag); } function start(): void { const [, chunk] = stream.next().value; const tag = chunk.slice(1); switch (tag) { case "html": { html(); break; } case "/html": case "head": case "/head": case "/body": { consumeUpToType("tag-end"); break; } case "title": { title(); break; } case "meta": { meta(); break; } case "body": { body(); break; } case "p": case "cite": case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": { text(tag); break; } default: { if (stream.next().done) { return; } throw new TypeError("Unexpected type"); } } } while (!stream.done) { start(); } page.buffers.forEach((x): void => { x.isReadOnly = true; }); if (page.previouslyInsertedContentNodeOffset) { page.previouslyInsertedContentNodeOffset = 0; } return page; }
the_stack
import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; import {SinonStub} from 'sinon'; import {describe, it, beforeEach, afterEach} from 'mocha'; import * as instancegroupmanagersModule from '../src'; import {PassThrough} from 'stream'; import {GoogleAuth, protobuf} from 'google-gax'; function generateSampleMessage<T extends object>(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message<T>, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject ) as T; } function stubSimpleCall<ResponseType>(response?: ResponseType, error?: Error) { return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); } function stubSimpleCallWithCallback<ResponseType>( response?: ResponseType, error?: Error ) { return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); } function stubPageStreamingCall<ResponseType>( responses?: ResponseType[], error?: Error ) { const pagingStub = sinon.stub(); if (responses) { for (let i = 0; i < responses.length; ++i) { pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } } const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; const mockStream = new PassThrough({ objectMode: true, transform: transformStub, }); // trigger as many responses as needed if (responses) { for (let i = 0; i < responses.length; ++i) { setImmediate(() => { mockStream.write({}); }); } setImmediate(() => { mockStream.end(); }); } else { setImmediate(() => { mockStream.write({}); }); setImmediate(() => { mockStream.end(); }); } return sinon.stub().returns(mockStream); } function stubAsyncIterationCall<ResponseType>( responses?: ResponseType[], error?: Error ) { let counter = 0; const asyncIterable = { [Symbol.asyncIterator]() { return { async next() { if (error) { return Promise.reject(error); } if (counter >= responses!.length) { return Promise.resolve({done: true, value: undefined}); } return Promise.resolve({done: false, value: responses![counter++]}); }, }; }, }; return sinon.stub().returns(asyncIterable); } describe('v1.InstanceGroupManagersClient', () => { let googleAuth: GoogleAuth; beforeEach(() => { googleAuth = { getClient: sinon.stub().resolves({ getRequestHeaders: sinon .stub() .resolves({Authorization: 'Bearer SOME_TOKEN'}), }), } as unknown as GoogleAuth; }); afterEach(() => { sinon.restore(); }); it('has servicePath', () => { const servicePath = instancegroupmanagersModule.v1.InstanceGroupManagersClient.servicePath; assert(servicePath); }); it('has apiEndpoint', () => { const apiEndpoint = instancegroupmanagersModule.v1.InstanceGroupManagersClient.apiEndpoint; assert(apiEndpoint); }); it('has port', () => { const port = instancegroupmanagersModule.v1.InstanceGroupManagersClient.port; assert(port); assert(typeof port === 'number'); }); it('should create a client with no option', () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient(); assert(client); }); it('should create a client with gRPC fallback', () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ fallback: true, }); assert(client); }); it('has initialize method and supports deferred initialization', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); assert.strictEqual(client.instanceGroupManagersStub, undefined); await client.initialize(); assert(client.instanceGroupManagersStub); }); it('has close method', () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.close(); }); it('has getProjectId method', async () => { const fakeProjectId = 'fake-project-id'; const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); const result = await client.getProjectId(); assert.strictEqual(result, fakeProjectId); assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); it('has getProjectId method with callback', async () => { const fakeProjectId = 'fake-project-id'; const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.auth.getProjectId = sinon .stub() .callsArgWith(0, null, fakeProjectId); const promise = new Promise((resolve, reject) => { client.getProjectId((err?: Error | null, projectId?: string | null) => { if (err) { reject(err); } else { resolve(projectId); } }); }); const result = await promise; assert.strictEqual(result, fakeProjectId); }); describe('abandonInstances', () => { it('invokes abandonInstances without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.AbandonInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.abandonInstances = stubSimpleCall(expectedResponse); const [response] = await client.abandonInstances(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.abandonInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes abandonInstances without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.AbandonInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.abandonInstances = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.abandonInstances( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.abandonInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes abandonInstances with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.AbandonInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.abandonInstances = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.abandonInstances(request), expectedError); assert( (client.innerApiCalls.abandonInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('applyUpdatesToInstances', () => { it('invokes applyUpdatesToInstances without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ApplyUpdatesToInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.applyUpdatesToInstances = stubSimpleCall(expectedResponse); const [response] = await client.applyUpdatesToInstances(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.applyUpdatesToInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes applyUpdatesToInstances without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ApplyUpdatesToInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.applyUpdatesToInstances = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.applyUpdatesToInstances( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.applyUpdatesToInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes applyUpdatesToInstances with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ApplyUpdatesToInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.applyUpdatesToInstances = stubSimpleCall( undefined, expectedError ); await assert.rejects( client.applyUpdatesToInstances(request), expectedError ); assert( (client.innerApiCalls.applyUpdatesToInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('createInstances', () => { it('invokes createInstances without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.CreateInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.createInstances = stubSimpleCall(expectedResponse); const [response] = await client.createInstances(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.createInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes createInstances without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.CreateInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.createInstances = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.createInstances( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.createInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes createInstances with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.CreateInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.createInstances = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.createInstances(request), expectedError); assert( (client.innerApiCalls.createInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('delete', () => { it('invokes delete without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DeleteInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.delete = stubSimpleCall(expectedResponse); const [response] = await client.delete(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.delete as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes delete without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DeleteInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.delete = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.delete( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.delete as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes delete with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DeleteInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.delete = stubSimpleCall(undefined, expectedError); await assert.rejects(client.delete(request), expectedError); assert( (client.innerApiCalls.delete as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('deleteInstances', () => { it('invokes deleteInstances without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DeleteInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.deleteInstances = stubSimpleCall(expectedResponse); const [response] = await client.deleteInstances(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.deleteInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes deleteInstances without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DeleteInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.deleteInstances = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.deleteInstances( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.deleteInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes deleteInstances with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DeleteInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.deleteInstances = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.deleteInstances(request), expectedError); assert( (client.innerApiCalls.deleteInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('deletePerInstanceConfigs', () => { it('invokes deletePerInstanceConfigs without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DeletePerInstanceConfigsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.deletePerInstanceConfigs = stubSimpleCall(expectedResponse); const [response] = await client.deletePerInstanceConfigs(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.deletePerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes deletePerInstanceConfigs without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DeletePerInstanceConfigsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.deletePerInstanceConfigs = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.deletePerInstanceConfigs( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.deletePerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes deletePerInstanceConfigs with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DeletePerInstanceConfigsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.deletePerInstanceConfigs = stubSimpleCall( undefined, expectedError ); await assert.rejects( client.deletePerInstanceConfigs(request), expectedError ); assert( (client.innerApiCalls.deletePerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('get', () => { it('invokes get without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ); client.innerApiCalls.get = stubSimpleCall(expectedResponse); const [response] = await client.get(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.get as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes get without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ); client.innerApiCalls.get = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.get( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IInstanceGroupManager | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.get as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes get with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.get = stubSimpleCall(undefined, expectedError); await assert.rejects(client.get(request), expectedError); assert( (client.innerApiCalls.get as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('insert', () => { it('invokes insert without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.InsertInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.insert = stubSimpleCall(expectedResponse); const [response] = await client.insert(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.insert as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes insert without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.InsertInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.insert = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.insert( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.insert as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes insert with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.InsertInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.insert = stubSimpleCall(undefined, expectedError); await assert.rejects(client.insert(request), expectedError); assert( (client.innerApiCalls.insert as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('patch', () => { it('invokes patch without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.PatchInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.patch = stubSimpleCall(expectedResponse); const [response] = await client.patch(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.patch as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes patch without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.PatchInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.patch = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.patch( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.patch as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes patch with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.PatchInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.patch = stubSimpleCall(undefined, expectedError); await assert.rejects(client.patch(request), expectedError); assert( (client.innerApiCalls.patch as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('patchPerInstanceConfigs', () => { it('invokes patchPerInstanceConfigs without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.PatchPerInstanceConfigsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.patchPerInstanceConfigs = stubSimpleCall(expectedResponse); const [response] = await client.patchPerInstanceConfigs(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.patchPerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes patchPerInstanceConfigs without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.PatchPerInstanceConfigsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.patchPerInstanceConfigs = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.patchPerInstanceConfigs( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.patchPerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes patchPerInstanceConfigs with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.PatchPerInstanceConfigsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.patchPerInstanceConfigs = stubSimpleCall( undefined, expectedError ); await assert.rejects( client.patchPerInstanceConfigs(request), expectedError ); assert( (client.innerApiCalls.patchPerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('recreateInstances', () => { it('invokes recreateInstances without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.RecreateInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.recreateInstances = stubSimpleCall(expectedResponse); const [response] = await client.recreateInstances(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.recreateInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes recreateInstances without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.RecreateInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.recreateInstances = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.recreateInstances( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.recreateInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes recreateInstances with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.RecreateInstancesInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.recreateInstances = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.recreateInstances(request), expectedError); assert( (client.innerApiCalls.recreateInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('resize', () => { it('invokes resize without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ResizeInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.resize = stubSimpleCall(expectedResponse); const [response] = await client.resize(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.resize as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes resize without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ResizeInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.resize = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.resize( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.resize as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes resize with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ResizeInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.resize = stubSimpleCall(undefined, expectedError); await assert.rejects(client.resize(request), expectedError); assert( (client.innerApiCalls.resize as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('setInstanceTemplate', () => { it('invokes setInstanceTemplate without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetInstanceTemplateInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.setInstanceTemplate = stubSimpleCall(expectedResponse); const [response] = await client.setInstanceTemplate(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.setInstanceTemplate as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes setInstanceTemplate without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetInstanceTemplateInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.setInstanceTemplate = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.setInstanceTemplate( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.setInstanceTemplate as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes setInstanceTemplate with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetInstanceTemplateInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.setInstanceTemplate = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.setInstanceTemplate(request), expectedError); assert( (client.innerApiCalls.setInstanceTemplate as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('setTargetPools', () => { it('invokes setTargetPools without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetTargetPoolsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.setTargetPools = stubSimpleCall(expectedResponse); const [response] = await client.setTargetPools(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.setTargetPools as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes setTargetPools without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetTargetPoolsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.setTargetPools = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.setTargetPools( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.setTargetPools as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes setTargetPools with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetTargetPoolsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.setTargetPools = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.setTargetPools(request), expectedError); assert( (client.innerApiCalls.setTargetPools as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('updatePerInstanceConfigs', () => { it('invokes updatePerInstanceConfigs without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.UpdatePerInstanceConfigsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.updatePerInstanceConfigs = stubSimpleCall(expectedResponse); const [response] = await client.updatePerInstanceConfigs(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.updatePerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes updatePerInstanceConfigs without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.UpdatePerInstanceConfigsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.updatePerInstanceConfigs = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.updatePerInstanceConfigs( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.updatePerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes updatePerInstanceConfigs with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.UpdatePerInstanceConfigsInstanceGroupManagerRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.updatePerInstanceConfigs = stubSimpleCall( undefined, expectedError ); await assert.rejects( client.updatePerInstanceConfigs(request), expectedError ); assert( (client.innerApiCalls.updatePerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('aggregatedList', () => { it('uses async iteration with aggregatedList without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.AggregatedListInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ [ 'tuple_key_1', generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManagersScopedList() ), ], [ 'tuple_key_2', generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManagersScopedList() ), ], [ 'tuple_key_3', generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManagersScopedList() ), ], ]; client.descriptors.page.aggregatedList.asyncIterate = stubAsyncIterationCall(expectedResponse); const responses: Array< [ string, protos.google.cloud.compute.v1.IInstanceGroupManagersScopedList ] > = []; const iterable = client.aggregatedListAsync(request); for await (const resource of iterable) { responses.push(resource!); } assert.deepStrictEqual(responses, expectedResponse); assert.deepStrictEqual( ( client.descriptors.page.aggregatedList.asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.aggregatedList.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with aggregatedList with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.AggregatedListInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.aggregatedList.asyncIterate = stubAsyncIterationCall(undefined, expectedError); const iterable = client.aggregatedListAsync(request); await assert.rejects(async () => { const responses: Array< [ string, protos.google.cloud.compute.v1.IInstanceGroupManagersScopedList ] > = []; for await (const resource of iterable) { responses.push(resource!); } }); assert.deepStrictEqual( ( client.descriptors.page.aggregatedList.asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.aggregatedList.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); }); describe('list', () => { it('invokes list without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), ]; client.innerApiCalls.list = stubSimpleCall(expectedResponse); const [response] = await client.list(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.list as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes list without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), ]; client.innerApiCalls.list = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.list( request, ( err?: Error | null, result?: | protos.google.cloud.compute.v1.IInstanceGroupManager[] | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.list as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes list with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.list = stubSimpleCall(undefined, expectedError); await assert.rejects(client.list(request), expectedError); assert( (client.innerApiCalls.list as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes listStream without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), ]; client.descriptors.page.list.createStream = stubPageStreamingCall(expectedResponse); const stream = client.listStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.InstanceGroupManager[] = []; stream.on( 'data', (response: protos.google.cloud.compute.v1.InstanceGroupManager) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); const responses = await promise; assert.deepStrictEqual(responses, expectedResponse); assert( (client.descriptors.page.list.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.list, request) ); assert.strictEqual( (client.descriptors.page.list.createStream as SinonStub).getCall(0) .args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('invokes listStream with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.list.createStream = stubPageStreamingCall( undefined, expectedError ); const stream = client.listStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.InstanceGroupManager[] = []; stream.on( 'data', (response: protos.google.cloud.compute.v1.InstanceGroupManager) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); await assert.rejects(promise, expectedError); assert( (client.descriptors.page.list.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.list, request) ); assert.strictEqual( (client.descriptors.page.list.createStream as SinonStub).getCall(0) .args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with list without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceGroupManager() ), ]; client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(expectedResponse); const responses: protos.google.cloud.compute.v1.IInstanceGroupManager[] = []; const iterable = client.listAsync(request); for await (const resource of iterable) { responses.push(resource!); } assert.deepStrictEqual(responses, expectedResponse); assert.deepStrictEqual( (client.descriptors.page.list.asyncIterate as SinonStub).getCall(0) .args[1], request ); assert.strictEqual( (client.descriptors.page.list.asyncIterate as SinonStub).getCall(0) .args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with list with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.list.asyncIterate = stubAsyncIterationCall( undefined, expectedError ); const iterable = client.listAsync(request); await assert.rejects(async () => { const responses: protos.google.cloud.compute.v1.IInstanceGroupManager[] = []; for await (const resource of iterable) { responses.push(resource!); } }); assert.deepStrictEqual( (client.descriptors.page.list.asyncIterate as SinonStub).getCall(0) .args[1], request ); assert.strictEqual( (client.descriptors.page.list.asyncIterate as SinonStub).getCall(0) .args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); }); describe('listErrors', () => { it('invokes listErrors without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListErrorsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), ]; client.innerApiCalls.listErrors = stubSimpleCall(expectedResponse); const [response] = await client.listErrors(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.listErrors as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes listErrors without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListErrorsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), ]; client.innerApiCalls.listErrors = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.listErrors( request, ( err?: Error | null, result?: | protos.google.cloud.compute.v1.IInstanceManagedByIgmError[] | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.listErrors as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes listErrors with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListErrorsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.listErrors = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.listErrors(request), expectedError); assert( (client.innerApiCalls.listErrors as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes listErrorsStream without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListErrorsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), ]; client.descriptors.page.listErrors.createStream = stubPageStreamingCall(expectedResponse); const stream = client.listErrorsStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.InstanceManagedByIgmError[] = []; stream.on( 'data', ( response: protos.google.cloud.compute.v1.InstanceManagedByIgmError ) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); const responses = await promise; assert.deepStrictEqual(responses, expectedResponse); assert( (client.descriptors.page.listErrors.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.listErrors, request) ); assert.strictEqual( (client.descriptors.page.listErrors.createStream as SinonStub).getCall( 0 ).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('invokes listErrorsStream with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListErrorsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.listErrors.createStream = stubPageStreamingCall( undefined, expectedError ); const stream = client.listErrorsStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.InstanceManagedByIgmError[] = []; stream.on( 'data', ( response: protos.google.cloud.compute.v1.InstanceManagedByIgmError ) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); await assert.rejects(promise, expectedError); assert( (client.descriptors.page.listErrors.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.listErrors, request) ); assert.strictEqual( (client.descriptors.page.listErrors.createStream as SinonStub).getCall( 0 ).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with listErrors without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListErrorsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), generateSampleMessage( new protos.google.cloud.compute.v1.InstanceManagedByIgmError() ), ]; client.descriptors.page.listErrors.asyncIterate = stubAsyncIterationCall(expectedResponse); const responses: protos.google.cloud.compute.v1.IInstanceManagedByIgmError[] = []; const iterable = client.listErrorsAsync(request); for await (const resource of iterable) { responses.push(resource!); } assert.deepStrictEqual(responses, expectedResponse); assert.deepStrictEqual( (client.descriptors.page.listErrors.asyncIterate as SinonStub).getCall( 0 ).args[1], request ); assert.strictEqual( (client.descriptors.page.listErrors.asyncIterate as SinonStub).getCall( 0 ).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with listErrors with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListErrorsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.listErrors.asyncIterate = stubAsyncIterationCall( undefined, expectedError ); const iterable = client.listErrorsAsync(request); await assert.rejects(async () => { const responses: protos.google.cloud.compute.v1.IInstanceManagedByIgmError[] = []; for await (const resource of iterable) { responses.push(resource!); } }); assert.deepStrictEqual( (client.descriptors.page.listErrors.asyncIterate as SinonStub).getCall( 0 ).args[1], request ); assert.strictEqual( (client.descriptors.page.listErrors.asyncIterate as SinonStub).getCall( 0 ).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); }); describe('listManagedInstances', () => { it('invokes listManagedInstances without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListManagedInstancesInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), ]; client.innerApiCalls.listManagedInstances = stubSimpleCall(expectedResponse); const [response] = await client.listManagedInstances(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.listManagedInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes listManagedInstances without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListManagedInstancesInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), ]; client.innerApiCalls.listManagedInstances = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.listManagedInstances( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IManagedInstance[] | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.listManagedInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes listManagedInstances with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListManagedInstancesInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.listManagedInstances = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.listManagedInstances(request), expectedError); assert( (client.innerApiCalls.listManagedInstances as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes listManagedInstancesStream without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListManagedInstancesInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), ]; client.descriptors.page.listManagedInstances.createStream = stubPageStreamingCall(expectedResponse); const stream = client.listManagedInstancesStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.ManagedInstance[] = []; stream.on( 'data', (response: protos.google.cloud.compute.v1.ManagedInstance) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); const responses = await promise; assert.deepStrictEqual(responses, expectedResponse); assert( (client.descriptors.page.listManagedInstances.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.listManagedInstances, request) ); assert.strictEqual( ( client.descriptors.page.listManagedInstances.createStream as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('invokes listManagedInstancesStream with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListManagedInstancesInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.listManagedInstances.createStream = stubPageStreamingCall(undefined, expectedError); const stream = client.listManagedInstancesStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.ManagedInstance[] = []; stream.on( 'data', (response: protos.google.cloud.compute.v1.ManagedInstance) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); await assert.rejects(promise, expectedError); assert( (client.descriptors.page.listManagedInstances.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.listManagedInstances, request) ); assert.strictEqual( ( client.descriptors.page.listManagedInstances.createStream as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with listManagedInstances without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListManagedInstancesInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), generateSampleMessage( new protos.google.cloud.compute.v1.ManagedInstance() ), ]; client.descriptors.page.listManagedInstances.asyncIterate = stubAsyncIterationCall(expectedResponse); const responses: protos.google.cloud.compute.v1.IManagedInstance[] = []; const iterable = client.listManagedInstancesAsync(request); for await (const resource of iterable) { responses.push(resource!); } assert.deepStrictEqual(responses, expectedResponse); assert.deepStrictEqual( ( client.descriptors.page.listManagedInstances.asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.listManagedInstances.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with listManagedInstances with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListManagedInstancesInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.listManagedInstances.asyncIterate = stubAsyncIterationCall(undefined, expectedError); const iterable = client.listManagedInstancesAsync(request); await assert.rejects(async () => { const responses: protos.google.cloud.compute.v1.IManagedInstance[] = []; for await (const resource of iterable) { responses.push(resource!); } }); assert.deepStrictEqual( ( client.descriptors.page.listManagedInstances.asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.listManagedInstances.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); }); describe('listPerInstanceConfigs', () => { it('invokes listPerInstanceConfigs without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListPerInstanceConfigsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), ]; client.innerApiCalls.listPerInstanceConfigs = stubSimpleCall(expectedResponse); const [response] = await client.listPerInstanceConfigs(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.listPerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes listPerInstanceConfigs without error using callback', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListPerInstanceConfigsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), ]; client.innerApiCalls.listPerInstanceConfigs = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.listPerInstanceConfigs( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IPerInstanceConfig[] | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.listPerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes listPerInstanceConfigs with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListPerInstanceConfigsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.listPerInstanceConfigs = stubSimpleCall( undefined, expectedError ); await assert.rejects( client.listPerInstanceConfigs(request), expectedError ); assert( (client.innerApiCalls.listPerInstanceConfigs as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes listPerInstanceConfigsStream without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListPerInstanceConfigsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), ]; client.descriptors.page.listPerInstanceConfigs.createStream = stubPageStreamingCall(expectedResponse); const stream = client.listPerInstanceConfigsStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.PerInstanceConfig[] = []; stream.on( 'data', (response: protos.google.cloud.compute.v1.PerInstanceConfig) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); const responses = await promise; assert.deepStrictEqual(responses, expectedResponse); assert( ( client.descriptors.page.listPerInstanceConfigs .createStream as SinonStub ) .getCall(0) .calledWith(client.innerApiCalls.listPerInstanceConfigs, request) ); assert.strictEqual( ( client.descriptors.page.listPerInstanceConfigs .createStream as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('invokes listPerInstanceConfigsStream with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListPerInstanceConfigsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.listPerInstanceConfigs.createStream = stubPageStreamingCall(undefined, expectedError); const stream = client.listPerInstanceConfigsStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.PerInstanceConfig[] = []; stream.on( 'data', (response: protos.google.cloud.compute.v1.PerInstanceConfig) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); await assert.rejects(promise, expectedError); assert( ( client.descriptors.page.listPerInstanceConfigs .createStream as SinonStub ) .getCall(0) .calledWith(client.innerApiCalls.listPerInstanceConfigs, request) ); assert.strictEqual( ( client.descriptors.page.listPerInstanceConfigs .createStream as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with listPerInstanceConfigs without error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListPerInstanceConfigsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), generateSampleMessage( new protos.google.cloud.compute.v1.PerInstanceConfig() ), ]; client.descriptors.page.listPerInstanceConfigs.asyncIterate = stubAsyncIterationCall(expectedResponse); const responses: protos.google.cloud.compute.v1.IPerInstanceConfig[] = []; const iterable = client.listPerInstanceConfigsAsync(request); for await (const resource of iterable) { responses.push(resource!); } assert.deepStrictEqual(responses, expectedResponse); assert.deepStrictEqual( ( client.descriptors.page.listPerInstanceConfigs .asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.listPerInstanceConfigs .asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with listPerInstanceConfigs with error', async () => { const client = new instancegroupmanagersModule.v1.InstanceGroupManagersClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListPerInstanceConfigsInstanceGroupManagersRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.listPerInstanceConfigs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); const iterable = client.listPerInstanceConfigsAsync(request); await assert.rejects(async () => { const responses: protos.google.cloud.compute.v1.IPerInstanceConfig[] = []; for await (const resource of iterable) { responses.push(resource!); } }); assert.deepStrictEqual( ( client.descriptors.page.listPerInstanceConfigs .asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.listPerInstanceConfigs .asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); }); });
the_stack
import type {Mutable, Proto, ObserverType} from "@swim/util"; import type {FastenerOwner, FastenerFlags} from "@swim/component"; import type {Model} from "../model/Model"; import type {AnyTrait, Trait} from "./Trait"; import {TraitRelationInit, TraitRelationClass, TraitRelation} from "./TraitRelation"; /** @internal */ export type TraitSetType<F extends TraitSet<any, any>> = F extends TraitSet<any, infer T> ? T : never; /** @public */ export interface TraitSetInit<T extends Trait = Trait> extends TraitRelationInit<T> { extends?: {prototype: TraitSet<any, any>} | string | boolean | null; key?(trait: T): string | undefined; compare?(a: T, b: T): number; sorted?: boolean; willSort?(parent: Model | null): void; didSort?(parent: Model | null): void; sortChildren?(parent: Model): void; compareChildren?(a: Trait, b: Trait): number; } /** @public */ export type TraitSetDescriptor<O = unknown, T extends Trait = Trait, I = {}> = ThisType<TraitSet<O, T> & I> & TraitSetInit<T> & Partial<I>; /** @public */ export interface TraitSetClass<F extends TraitSet<any, any> = TraitSet<any, any>> extends TraitRelationClass<F> { /** @internal */ readonly SortedFlag: FastenerFlags; /** @internal @override */ readonly FlagShift: number; /** @internal @override */ readonly FlagMask: FastenerFlags; } /** @public */ export interface TraitSetFactory<F extends TraitSet<any, any> = TraitSet<any, any>> extends TraitSetClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): TraitSetFactory<F> & I; define<O, T extends Trait = Trait>(className: string, descriptor: TraitSetDescriptor<O, T>): TraitSetFactory<TraitSet<any, T>>; define<O, T extends Trait = Trait>(className: string, descriptor: {observes: boolean} & TraitSetDescriptor<O, T, ObserverType<T>>): TraitSetFactory<TraitSet<any, T>>; define<O, T extends Trait = Trait, I = {}>(className: string, descriptor: {implements: unknown} & TraitSetDescriptor<O, T, I>): TraitSetFactory<TraitSet<any, T> & I>; define<O, T extends Trait = Trait, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & TraitSetDescriptor<O, T, I & ObserverType<T>>): TraitSetFactory<TraitSet<any, T> & I>; <O, T extends Trait = Trait>(descriptor: TraitSetDescriptor<O, T>): PropertyDecorator; <O, T extends Trait = Trait>(descriptor: {observes: boolean} & TraitSetDescriptor<O, T, ObserverType<T>>): PropertyDecorator; <O, T extends Trait = Trait, I = {}>(descriptor: {implements: unknown} & TraitSetDescriptor<O, T, I>): PropertyDecorator; <O, T extends Trait = Trait, I = {}>(descriptor: {implements: unknown; observes: boolean} & TraitSetDescriptor<O, T, I & ObserverType<T>>): PropertyDecorator; } /** @public */ export interface TraitSet<O = unknown, T extends Trait = Trait> extends TraitRelation<O, T> { (trait: AnyTrait<T>): O; /** @override */ get fastenerType(): Proto<TraitSet<any, any>>; /** @internal */ readonly traits: {readonly [traitId: number]: T | undefined}; readonly traitCount: number; hasTrait(trait: Trait): boolean; addTrait(trait?: AnyTrait<T>, target?: Trait | null, key?: string): T; attachTrait(trait?: AnyTrait<T>, target?: Trait | null): T; detachTrait(trait: T): T | null; insertTrait(model?: Model | null, trait?: AnyTrait<T>, target?: Trait | null, key?: string): T; removeTrait(trait: T): T | null; deleteTrait(trait: T): T | null; /** @internal @override */ bindModel(model: Model, target: Model | null): void; /** @internal @override */ unbindModel(model: Model): void; /** @override */ detectModel(model: Model): T | null; /** @internal @override */ bindTrait(trait: Trait, target: Trait | null): void; /** @internal @override */ unbindTrait(trait: Trait): void; /** @override */ detectTrait(trait: Trait): T | null; /** @internal @protected */ key(trait: T): string | undefined; get sorted(): boolean; /** @internal */ initSorted(sorted: boolean): void; sort(sorted?: boolean): this; /** @protected */ willSort(parent: Model | null): void; /** @protected */ onSort(parent: Model | null): void; /** @protected */ didSort(parent: Model | null): void; /** @internal @protected */ sortChildren(parent: Model): void; /** @internal */ compareChildren(a: Trait, b: Trait): number; /** @internal @protected */ compare(a: T, b: T): number; } /** @public */ export const TraitSet = (function (_super: typeof TraitRelation) { const TraitSet: TraitSetFactory = _super.extend("TraitSet"); Object.defineProperty(TraitSet.prototype, "fastenerType", { get: function (this: TraitSet): Proto<TraitSet<any, any>> { return TraitSet; }, configurable: true, }); TraitSet.prototype.hasTrait = function (this: TraitSet, trait: Trait): boolean { return this.traits[trait.uid] !== void 0; }; TraitSet.prototype.addTrait = function <T extends Trait>(this: TraitSet<unknown, T>, newTrait?: AnyTrait<T>, target?: Trait | null, key?: string): T { if (newTrait !== void 0 && newTrait !== null) { newTrait = this.fromAny(newTrait); } else { newTrait = this.createTrait(); } if (target === void 0) { target = null; } let model: Model | null; if (this.binds && (model = this.parentModel, model !== null)) { if (key === void 0) { key = this.key(newTrait); } this.insertChild(model, newTrait, target, key); } const traits = this.traits as {[traitId: number]: T | undefined}; if (traits[newTrait.uid] === void 0) { this.willAttachTrait(newTrait, target); traits[newTrait.uid] = newTrait; (this as Mutable<typeof this>).traitCount += 1; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } return newTrait; }; TraitSet.prototype.attachTrait = function <T extends Trait>(this: TraitSet<unknown, T>, newTrait?: AnyTrait<T>, target?: Trait | null): T { if (newTrait !== void 0 && newTrait !== null) { newTrait = this.fromAny(newTrait); } else { newTrait = this.createTrait(); } const traits = this.traits as {[traitId: number]: T | undefined}; if (traits[newTrait.uid] === void 0) { if (target === void 0) { target = null; } this.willAttachTrait(newTrait, target); traits[newTrait.uid] = newTrait; (this as Mutable<typeof this>).traitCount += 1; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } return newTrait; }; TraitSet.prototype.detachTrait = function <T extends Trait>(this: TraitSet<unknown, T>, oldTrait: T): T | null { const traits = this.traits as {[traitId: number]: T | undefined}; if (traits[oldTrait.uid] !== void 0) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).traitCount -= 1; delete traits[oldTrait.uid]; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); return oldTrait; } return null; }; TraitSet.prototype.insertTrait = function <T extends Trait>(this: TraitSet<unknown, T>, model?: Model | null, newTrait?: AnyTrait<T>, target?: Trait | null, key?: string): T { if (newTrait !== void 0 && newTrait !== null) { newTrait = this.fromAny(newTrait); } else { newTrait = this.createTrait(); } if (model === void 0 || model === null) { model = this.parentModel; } if (target === void 0) { target = null; } if (key === void 0) { key = this.key(newTrait); } if (model !== null && (newTrait.model !== model || newTrait.key !== key)) { this.insertChild(model, newTrait, target, key); } const traits = this.traits as {[traitId: number]: T | undefined}; if (traits[newTrait.uid] === void 0) { this.willAttachTrait(newTrait, target); traits[newTrait.uid] = newTrait; (this as Mutable<typeof this>).traitCount += 1; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } return newTrait; }; TraitSet.prototype.removeTrait = function <T extends Trait>(this: TraitSet<unknown, T>, trait: T): T | null { if (this.hasTrait(trait)) { trait.remove(); return trait; } return null; }; TraitSet.prototype.deleteTrait = function <T extends Trait>(this: TraitSet<unknown, T>, trait: T): T | null { const oldTrait = this.detachTrait(trait); if (oldTrait !== null) { oldTrait.remove(); } return oldTrait; }; TraitSet.prototype.bindModel = function <T extends Trait>(this: TraitSet<unknown, T>, model: Model, target: Model | null): void { if (this.binds) { const newTrait = this.detectModel(model); const traits = this.traits as {[traitId: number]: T | undefined}; if (newTrait !== null && traits[newTrait.uid] === void 0) { this.willAttachTrait(newTrait, null); traits[newTrait.uid] = newTrait; (this as Mutable<typeof this>).traitCount += 1; this.onAttachTrait(newTrait, null); this.initTrait(newTrait); this.didAttachTrait(newTrait, null); } } }; TraitSet.prototype.unbindModel = function <T extends Trait>(this: TraitSet<unknown, T>, model: Model): void { if (this.binds) { const oldTrait = this.detectModel(model); const traits = this.traits as {[traitId: number]: T | undefined}; if (oldTrait !== null && traits[oldTrait.uid] !== void 0) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).traitCount -= 1; delete traits[oldTrait.uid]; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } } }; TraitSet.prototype.detectModel = function <T extends Trait>(this: TraitSet<unknown, T>, model: Model): T | null { return null; }; TraitSet.prototype.bindTrait = function <T extends Trait>(this: TraitSet<unknown, T>, trait: Trait, target: Trait | null): void { if (this.binds) { const newTrait = this.detectTrait(trait); const traits = this.traits as {[traitId: number]: T | undefined}; if (newTrait !== null && traits[newTrait.uid] === void 0) { this.willAttachTrait(newTrait, target); traits[newTrait.uid] = newTrait; (this as Mutable<typeof this>).traitCount += 1; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } } }; TraitSet.prototype.unbindTrait = function <T extends Trait>(this: TraitSet<unknown, T>, trait: Trait): void { if (this.binds) { const oldTrait = this.detectTrait(trait); const traits = this.traits as {[traitId: number]: T | undefined}; if (oldTrait !== null && traits[oldTrait.uid] !== void 0) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).traitCount -= 1; delete traits[oldTrait.uid]; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } } }; TraitSet.prototype.detectTrait = function <T extends Trait>(this: TraitSet<unknown, T>, trait: Trait): T | null { if (typeof this.type === "function" && trait instanceof this.type) { return trait as T; } return null; }; TraitSet.prototype.key = function <T extends Trait>(this: TraitSet<unknown, T>, trait: T): string | undefined { return void 0; }; Object.defineProperty(TraitSet.prototype, "sorted", { get(this: TraitSet): boolean { return (this.flags & TraitSet.SortedFlag) !== 0; }, configurable: true, }); TraitSet.prototype.initInherits = function (this: TraitSet, sorted: boolean): void { if (sorted) { (this as Mutable<typeof this>).flags = this.flags | TraitSet.SortedFlag; } else { (this as Mutable<typeof this>).flags = this.flags & ~TraitSet.SortedFlag; } }; TraitSet.prototype.sort = function (this: TraitSet, sorted?: boolean): typeof this { if (sorted === void 0) { sorted = true; } const flags = this.flags; if (sorted && (flags & TraitSet.SortedFlag) === 0) { const parent = this.parentModel; this.willSort(parent); this.setFlags(flags | TraitSet.SortedFlag); this.onSort(parent); this.didSort(parent); } else if (!sorted && (flags & TraitSet.SortedFlag) !== 0) { this.setFlags(flags & ~TraitSet.SortedFlag); } return this; }; TraitSet.prototype.willSort = function (this: TraitSet, parent: Model | null): void { // hook }; TraitSet.prototype.onSort = function (this: TraitSet, parent: Model | null): void { if (parent !== null) { this.sortChildren(parent); } }; TraitSet.prototype.didSort = function (this: TraitSet, parent: Model | null): void { // hook }; TraitSet.prototype.sortChildren = function <T extends Trait>(this: TraitSet<unknown, T>, parent: Model): void { parent.sortTraits(this.compareChildren.bind(this)); }; TraitSet.prototype.compareChildren = function <T extends Trait>(this: TraitSet<unknown, T>, a: Trait, b: Trait): number { const traits = this.traits; const x = traits[a.uid]; const y = traits[b.uid]; if (x !== void 0 && y !== void 0) { return this.compare(x, y); } else { return x !== void 0 ? 1 : y !== void 0 ? -1 : 0; } }; TraitSet.prototype.compare = function <T extends Trait>(this: TraitSet<unknown, T>, a: T, b: T): number { return a.uid < b.uid ? -1 : a.uid > b.uid ? 1 : 0; }; TraitSet.construct = function <F extends TraitSet<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { if (fastener === null) { fastener = function (newTrait: AnyTrait<TraitSetType<F>>): FastenerOwner<F> { fastener!.addTrait(newTrait); return fastener!.owner; } as F; delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name Object.setPrototypeOf(fastener, fastenerClass.prototype); } fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).traits = {}; (fastener as Mutable<typeof fastener>).traitCount = 0; return fastener; }; TraitSet.define = function <O, T extends Trait>(className: string, descriptor: TraitSetDescriptor<O, T>): TraitSetFactory<TraitSet<any, T>> { let superClass = descriptor.extends as TraitSetFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const sorted = descriptor.sorted; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.sorted; if (superClass === void 0 || superClass === null) { superClass = this; } const fastenerClass = superClass.extend(className, descriptor); fastenerClass.construct = function (fastenerClass: {prototype: TraitSet<any, any>}, fastener: TraitSet<O, T> | null, owner: O): TraitSet<O, T> { fastener = superClass!.construct(fastenerClass, fastener, owner); if (affinity !== void 0) { fastener.initAffinity(affinity); } if (inherits !== void 0) { fastener.initInherits(inherits); } if (sorted !== void 0) { fastener.initSorted(sorted); } return fastener; }; return fastenerClass; }; (TraitSet as Mutable<typeof TraitSet>).SortedFlag = 1 << (_super.FlagShift + 0); (TraitSet as Mutable<typeof TraitSet>).FlagShift = _super.FlagShift + 1; (TraitSet as Mutable<typeof TraitSet>).FlagMask = (1 << TraitSet.FlagShift) - 1; return TraitSet; })(TraitRelation);
the_stack
import { EventEnvelope, EventItem, TransportMakeRequestResponse } from '@sentry/types'; import { createEnvelope, PromiseBuffer, resolvedSyncPromise, serializeEnvelope } from '@sentry/utils'; import { TextEncoder } from 'util'; import { createTransport } from '../../../src/transports/base'; const ERROR_ENVELOPE = createEnvelope<EventEnvelope>({ event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2', sent_at: '123' }, [ [{ type: 'event' }, { event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2' }] as EventItem, ]); const TRANSACTION_ENVELOPE = createEnvelope<EventEnvelope>( { event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2', sent_at: '123' }, [[{ type: 'transaction' }, { event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2' }] as EventItem], ); const transportOptions = { recordDroppedEvent: () => undefined, // noop textEncoder: new TextEncoder(), }; describe('createTransport', () => { it('flushes the buffer', async () => { const mockBuffer: PromiseBuffer<void> = { $: [], add: jest.fn(), drain: jest.fn(), }; const transport = createTransport(transportOptions, _ => resolvedSyncPromise({}), mockBuffer); /* eslint-disable @typescript-eslint/unbound-method */ expect(mockBuffer.drain).toHaveBeenCalledTimes(0); await transport.flush(1000); expect(mockBuffer.drain).toHaveBeenCalledTimes(1); expect(mockBuffer.drain).toHaveBeenLastCalledWith(1000); /* eslint-enable @typescript-eslint/unbound-method */ }); describe('send', () => { it('constructs a request to send to Sentry', async () => { expect.assertions(1); const transport = createTransport(transportOptions, req => { expect(req.body).toEqual(serializeEnvelope(ERROR_ENVELOPE, new TextEncoder())); return resolvedSyncPromise({}); }); await transport.send(ERROR_ENVELOPE); }); it('does throw if request fails', async () => { expect.assertions(2); const transport = createTransport(transportOptions, req => { expect(req.body).toEqual(serializeEnvelope(ERROR_ENVELOPE, new TextEncoder())); throw new Error(); }); expect(() => { void transport.send(ERROR_ENVELOPE); }).toThrow(); }); describe('Rate-limiting', () => { function setRateLimitTimes(): { retryAfterSeconds: number; beforeLimit: number; withinLimit: number; afterLimit: number; } { const retryAfterSeconds = 10; const beforeLimit = Date.now(); const withinLimit = beforeLimit + (retryAfterSeconds / 2) * 1000; const afterLimit = beforeLimit + retryAfterSeconds * 1000; return { retryAfterSeconds, beforeLimit, withinLimit, afterLimit }; } function createTestTransport(initialTransportResponse: TransportMakeRequestResponse) { let transportResponse: TransportMakeRequestResponse = initialTransportResponse; function setTransportResponse(res: TransportMakeRequestResponse) { transportResponse = res; } const mockRequestExecutor = jest.fn(_ => { return resolvedSyncPromise(transportResponse); }); const mockRecordDroppedEventCallback = jest.fn(); const transport = createTransport( { recordDroppedEvent: mockRecordDroppedEventCallback, textEncoder: new TextEncoder() }, mockRequestExecutor, ); return [transport, setTransportResponse, mockRequestExecutor, mockRecordDroppedEventCallback] as const; } it('back-off _after_ Retry-After header was received', async () => { const { retryAfterSeconds, beforeLimit, withinLimit, afterLimit } = setRateLimitTimes(); const [transport, setTransportResponse, requestExecutor, recordDroppedEventCallback] = createTestTransport({}); const dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => beforeLimit); await transport.send(ERROR_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); setTransportResponse({ headers: { 'x-sentry-rate-limits': null, 'retry-after': `${retryAfterSeconds}`, }, }); await transport.send(ERROR_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); // act like were in the rate limited period dateNowSpy.mockImplementation(() => withinLimit); await transport.send(ERROR_ENVELOPE); expect(requestExecutor).not.toHaveBeenCalled(); expect(recordDroppedEventCallback).toHaveBeenCalledWith('ratelimit_backoff', 'error'); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); // act like it's after the rate limited period dateNowSpy.mockImplementation(() => afterLimit); await transport.send(ERROR_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); }); it('back-off using X-Sentry-Rate-Limits with single category', async () => { const { retryAfterSeconds, beforeLimit, withinLimit, afterLimit } = setRateLimitTimes(); const [transport, setTransportResponse, requestExecutor, recordDroppedEventCallback] = createTestTransport({ headers: { 'x-sentry-rate-limits': `${retryAfterSeconds}:error:scope`, 'retry-after': null, }, }); const dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => beforeLimit); await transport.send(ERROR_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); setTransportResponse({}); // act like were in the rate limited period dateNowSpy.mockImplementation(() => withinLimit); await transport.send(TRANSACTION_ENVELOPE); // Transaction envelope should be sent expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); await transport.send(ERROR_ENVELOPE); // Error envelope should not be sent because of pending rate limit expect(requestExecutor).not.toHaveBeenCalled(); expect(recordDroppedEventCallback).toHaveBeenCalledWith('ratelimit_backoff', 'error'); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); // act like it's after the rate limited period dateNowSpy.mockImplementation(() => afterLimit); await transport.send(TRANSACTION_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); await transport.send(ERROR_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); }); it('back-off using X-Sentry-Rate-Limits with multiple categories', async () => { const { retryAfterSeconds, beforeLimit, withinLimit, afterLimit } = setRateLimitTimes(); const [transport, setTransportResponse, requestExecutor, recordDroppedEventCallback] = createTestTransport({ headers: { 'x-sentry-rate-limits': `${retryAfterSeconds}:error;transaction:scope`, 'retry-after': null, }, }); const dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => beforeLimit); await transport.send(ERROR_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); setTransportResponse({}); // act like were in the rate limited period dateNowSpy.mockImplementation(() => withinLimit); await transport.send(TRANSACTION_ENVELOPE); // Transaction envelope should not be sent because of pending rate limit expect(requestExecutor).not.toHaveBeenCalled(); expect(recordDroppedEventCallback).toHaveBeenCalledWith('ratelimit_backoff', 'transaction'); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); await transport.send(ERROR_ENVELOPE); // Error envelope should not be sent because of pending rate limit expect(requestExecutor).not.toHaveBeenCalled(); expect(recordDroppedEventCallback).toHaveBeenCalledWith('ratelimit_backoff', 'error'); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); // act like it's after the rate limited period dateNowSpy.mockImplementation(() => afterLimit); await transport.send(TRANSACTION_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); await transport.send(ERROR_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); }); it('back-off using X-Sentry-Rate-Limits with missing categories should lock them all', async () => { const { retryAfterSeconds, beforeLimit, withinLimit, afterLimit } = setRateLimitTimes(); const [transport, setTransportResponse, requestExecutor, recordDroppedEventCallback] = createTestTransport({ headers: { 'x-sentry-rate-limits': `${retryAfterSeconds}::scope`, 'retry-after': null, }, }); const dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => beforeLimit); await transport.send(ERROR_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); setTransportResponse({}); // act like were in the rate limited period dateNowSpy.mockImplementation(() => withinLimit); await transport.send(TRANSACTION_ENVELOPE); // Transaction envelope should not be sent because of pending rate limit expect(requestExecutor).not.toHaveBeenCalled(); expect(recordDroppedEventCallback).toHaveBeenCalledWith('ratelimit_backoff', 'transaction'); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); await transport.send(ERROR_ENVELOPE); // Error envelope should not be sent because of pending rate limit expect(requestExecutor).not.toHaveBeenCalled(); expect(recordDroppedEventCallback).toHaveBeenCalledWith('ratelimit_backoff', 'error'); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); // act like it's after the rate limited period dateNowSpy.mockImplementation(() => afterLimit); await transport.send(TRANSACTION_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); requestExecutor.mockClear(); recordDroppedEventCallback.mockClear(); await transport.send(ERROR_ENVELOPE); expect(requestExecutor).toHaveBeenCalledTimes(1); expect(recordDroppedEventCallback).not.toHaveBeenCalled(); }); }); }); });
the_stack
import React, {MouseEvent, RefObject, useEffect, useRef, useState} from 'react'; import {useForceUpdate} from '../../basic/utils'; import { DRAG_DEVIATION, FILLER_MIN_WIDTH, HEADER_HEIGHT, MAX_COLUMN_WIDTH, MIN_COLUMN_WIDTH, RESIZE_DEVIATION, ROW_HEIGHT, ROW_NO_WIDTH } from '../constants'; import {useGridEventBus} from '../grid-event-bus'; import {GridEventTypes} from '../grid-event-bus-types'; import {ColumnDefs, ColumnSortBy, DataColumnDef, DataSetState, SelectionRef} from '../types'; import {Grid} from './grid'; import {GridDragColumn} from './grid-drag-column'; import {GridScrollShade} from './grid-scroll-shade'; import {GridSelection} from './grid-selection'; import {GridResizeShade, GridWrapperContainer} from './widgets'; enum Behavior { NONE = 'none', PICK_COLUMN = 'pick-column', CAN_RESIZE = 'can-resize', RESIZING = 'resizing', READY_TO_DRAG = 'ready-to-drag', DRAGGING = 'dragging' } interface PickedColumn { column: DataColumnDef; // offset-x between mouse down point to wrapper left offsetX: number; originalWidth: number; } interface PickColumnOptions { wrapperLeft: number; table: HTMLDivElement; mouseClientX: number; columnDefs: ColumnDefs; isFixTable: boolean; rowNoColumnWidth: number; } const findDataTable = (element: HTMLElement): HTMLDivElement | null => { const widgetType = element.getAttribute('data-widget'); if (widgetType !== 'dataset-grid') { return element.closest('div[data-widget="dataset-grid"]') as HTMLDivElement; } return element as HTMLDivElement; }; const computeTableColumnsRightPositions = (displayColumns: Array<DataColumnDef>) => { const widths = displayColumns.map(column => column.width); for (let index = 1, count = widths.length; index < count; index++) { widths[index] += widths[index - 1]; } return widths; }; const computeAndSetCursor = (options: { table: HTMLDivElement; mouseClientX: number; mouseClientY: number; isFixTable: boolean; rowNoColumnWidth: number; displayColumns: Array<DataColumnDef>; fixColumns: Array<DataColumnDef>; changeBehavior: (state: Behavior) => void; }) => { const { table, mouseClientX, mouseClientY, isFixTable, rowNoColumnWidth, displayColumns, fixColumns, changeBehavior } = options; const {top: containerTop, left: containerLeft} = table.getBoundingClientRect(); if (mouseClientY - containerTop > HEADER_HEIGHT) { // not in header changeBehavior(Behavior.NONE); return; } const left = mouseClientX - containerLeft; if (isFixTable && left <= rowNoColumnWidth) { // in row number column changeBehavior(Behavior.NONE); return; } // compute every resize point const widths = computeTableColumnsRightPositions(displayColumns); if (!isFixTable && left > widths[widths.length - 1] + RESIZE_DEVIATION - table.scrollLeft) { // in filler column changeBehavior(Behavior.NONE); return; } const offsetLeft = isFixTable ? left - rowNoColumnWidth : left; let canResize; if (isFixTable) { canResize = widths.some(width => Math.abs(width - offsetLeft) <= RESIZE_DEVIATION); } else { // resize self, or last fix column canResize = (fixColumns.length !== 0 && offsetLeft <= RESIZE_DEVIATION) || widths.some(width => Math.abs(width - offsetLeft - table.scrollLeft) <= RESIZE_DEVIATION); } changeBehavior(canResize ? Behavior.CAN_RESIZE : Behavior.PICK_COLUMN); }; const findPickedColumn = (options: PickColumnOptions & { matchColumnIndex: (widths: Array<number>, offsetLeft: number) => number }): PickedColumn => { const {wrapperLeft, table, mouseClientX, columnDefs, isFixTable, rowNoColumnWidth, matchColumnIndex} = options; const tableColumnDefs = isFixTable ? columnDefs.fixed : columnDefs.data; let offsetLeft: number; if (isFixTable) { offsetLeft = mouseClientX - table.getBoundingClientRect().left - rowNoColumnWidth; } else { offsetLeft = mouseClientX - table.getBoundingClientRect().left + table.scrollLeft; } const widths = computeTableColumnsRightPositions(tableColumnDefs); const index = matchColumnIndex(widths, offsetLeft); return { column: tableColumnDefs[index], offsetX: mouseClientX - wrapperLeft, originalWidth: tableColumnDefs[index].width }; }; const findPickedColumnForResize = (options: PickColumnOptions): PickedColumn => { const {wrapperLeft, table, mouseClientX, columnDefs, isFixTable} = options; if (!isFixTable && mouseClientX - table.getBoundingClientRect().left <= RESIZE_DEVIATION) { // to resize the last column of fix table return { column: columnDefs.fixed[columnDefs.fixed.length - 1], offsetX: mouseClientX - wrapperLeft, originalWidth: columnDefs.fixed[columnDefs.fixed.length - 1].width }; } const matchColumnIndex = (widths: Array<number>, offsetLeft: number) => { return widths.findIndex(width => Math.abs(width - offsetLeft) <= RESIZE_DEVIATION); }; return findPickedColumn({...options, matchColumnIndex}); }; const findPickedColumnForDrag = (options: PickColumnOptions): PickedColumn => { const matchColumnIndex = (widths: Array<number>, offsetLeft: number) => { return widths.findIndex((width, index) => { return width > offsetLeft && (index === 0 || widths[index - 1] < offsetLeft); }); }; return findPickedColumn({...options, matchColumnIndex}); }; const useDecorateFixStyle = (options: { fixTableRef: RefObject<HTMLDivElement>; dataTableRef: RefObject<HTMLDivElement>; }) => { const {fixTableRef, dataTableRef} = options; const arrangeFixedTableStyle = () => { if (!dataTableRef.current || !fixTableRef.current) { return; } const dataTable = dataTableRef.current; const fixTable = fixTableRef.current; const scrollBarHeight = dataTable.offsetHeight - dataTable.clientHeight; fixTable.style.height = `calc(100% - ${scrollBarHeight}px)`; fixTable.style.boxShadow = `0 1px 0 0 var(--border-color)`; }; // link scroll between fixed table and data table useEffect(() => { if (!dataTableRef.current || !fixTableRef.current) { return; } const dataTable = dataTableRef.current; const fixTable = fixTableRef.current; const onDataTableScroll = () => { arrangeFixedTableStyle(); fixTable.scrollTop = dataTable.scrollTop; }; setTimeout(arrangeFixedTableStyle, 100); dataTable.addEventListener('scroll', onDataTableScroll); // synchronize scroll top to data table const onFixTableScroll = () => dataTable.scrollTop = fixTable.scrollTop; fixTable.addEventListener('scroll', onFixTableScroll); return () => { dataTable.removeEventListener('scroll', onDataTableScroll); fixTable.removeEventListener('scroll', onFixTableScroll); }; }); return arrangeFixedTableStyle; }; export const GridWrapper = (props: { data: DataSetState; languagesSupport: boolean; }) => { const {data, languagesSupport} = props; const {columnDefs} = data; const {on, off, fire} = useGridEventBus(); const wrapperRef = useRef<HTMLDivElement | null>(null); const fixTableRef = useRef<HTMLDivElement | null>(null); const dataTableRef = useRef<HTMLDivElement | null>(null); const selectionRef = useRef<SelectionRef | null>(null); const [rowNoColumnWidth] = useState(ROW_NO_WIDTH); const [behavior, setBehavior] = useState<Behavior>(Behavior.NONE); const [pickedColumn, setPickedColumn] = useState<PickedColumn | null>(null); const forceUpdate = useForceUpdate(); const arrangeFixedTableStyle = useDecorateFixStyle({fixTableRef, dataTableRef}); useEffect(() => { const onColumnWidthCompress = () => { columnDefs.fixed.forEach(c => c.width = MIN_COLUMN_WIDTH); columnDefs.data.forEach(c => c.width = MIN_COLUMN_WIDTH); fire(GridEventTypes.REPAINT_SELECTION); forceUpdate(); }; on(GridEventTypes.COMPRESS_COLUMN_WIDTH, onColumnWidthCompress); return () => { off(GridEventTypes.COMPRESS_COLUMN_WIDTH, onColumnWidthCompress); }; }, [on, off, fire, columnDefs.fixed, columnDefs.data, forceUpdate]); const manageCursor = (options: { table: HTMLDivElement | null, mouseClientX: number, mouseClientY: number, avoidResize: boolean }) => { const {table} = options; if (!table) { // target is wrapper itself, when mouse in left-bottom corner and there is horizontal scroll bar shown return; } const {mouseClientX, mouseClientY, avoidResize} = options; computeAndSetCursor({ table, mouseClientX, mouseClientY, isFixTable: table === fixTableRef.current, rowNoColumnWidth, displayColumns: table === fixTableRef.current ? columnDefs.fixed : columnDefs.data, fixColumns: columnDefs.fixed, changeBehavior: avoidResize ? (state: Behavior) => { setBehavior(state === Behavior.CAN_RESIZE ? Behavior.PICK_COLUMN : state); } : setBehavior }); }; const resizeColumn = (mouseClientX: number) => { if (!pickedColumn) { return; } const {left: wrapperLeft} = wrapperRef.current!.getBoundingClientRect(); const movementX = mouseClientX - wrapperLeft - pickedColumn.offsetX; pickedColumn.column.width = Math.min(Math.max(MIN_COLUMN_WIDTH, pickedColumn.originalWidth + movementX), MAX_COLUMN_WIDTH); const isFixTable = columnDefs.fixed.includes(pickedColumn.column); const table = isFixTable ? fixTableRef.current! : dataTableRef.current!; const columns = isFixTable ? columnDefs.fixed : columnDefs.data; const header = table.querySelector('div[data-widget="dataset-grid-header"]')! as HTMLDivElement; const body = table.querySelector('div[data-widget="dataset-grid-body"]')! as HTMLDivElement; const gridTemplateColumns = header.style.gridTemplateColumns.split(' '); // physical column is on (definition column index + 1) * 2, starts from 1; // width declaration in grid template columns css also is on (definition column index + 1) * 2, starts from 0, therefore index must plus 1 additional; // in fix table, there are row number columns, one for show, one for keep rank with real columns. gridTemplateColumns[(columns.indexOf(pickedColumn.column) + (isFixTable ? 1 : 0)) * 2 + 1] = `${pickedColumn.column.width}px`; const newGridTemplateColumns = gridTemplateColumns.join(' '); header.style.gridTemplateColumns = newGridTemplateColumns; body.style.gridTemplateColumns = newGridTemplateColumns; if (isFixTable) { // left of data table doesn't change when resize column in fix table const dataTable = dataTableRef.current!; // css includes row number column here const left = gridTemplateColumns.map(width => parseInt(width)).reduce((total, width) => total + width, 0); dataTable.style.left = `${left}px`; dataTable.style.position = 'absolute'; dataTable.style.width = `calc(100% - ${left}px)`; } fire(GridEventTypes.REPAINT_SELECTION); arrangeFixedTableStyle(); }; // reset the placeholder columns width to zero, // reset the real columns width to original, // because don't know the previous status const resetGridTemplateColumns = (options: { element: HTMLDivElement; columns: Array<DataColumnDef>; isFixTable: boolean; }) => { const {element, columns, isFixTable} = options; const gridColumnCount = columns.length * 2; const shouldReset = (index: number) => isFixTable ? (index > 1 && index < gridColumnCount + 3) : (index < gridColumnCount + 1); const getDefIndex = (index: number) => isFixTable ? ((index - 3) / 2) : ((index - 1) / 2); return element.style.gridTemplateColumns.split(' ').map((width, index) => { if (shouldReset(index)) { // recover all width return (index % 2 === 0) ? '0px' : `${columns[getDefIndex(index)].width}px`; } else { // last minmax column return width; } }); }; const repaintWhenDragging = (options: { mouseClientX: number; sourceTable: HTMLDivElement; sourceColumns: Array<DataColumnDef>; targetTable: HTMLDivElement; targetColumns: Array<DataColumnDef>; pickedColumn: DataColumnDef; }) => { const { mouseClientX, sourceTable, sourceColumns, targetTable, targetColumns, pickedColumn } = options; // handle source table const dragColumnIndex = sourceColumns.indexOf(pickedColumn); const sourceHeader = sourceTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-header"]')!; const sourceBody = sourceTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-body"]')!; const sourceIsFixTable = sourceTable === fixTableRef.current; const sourceGridTemplateColumns = resetGridTemplateColumns({ element: sourceHeader, columns: sourceColumns, isFixTable: sourceIsFixTable }); if (sourceIsFixTable) { sourceGridTemplateColumns[(dragColumnIndex + 1) * 2 + 1] = '0'; } else { sourceGridTemplateColumns[(dragColumnIndex + 1) * 2 - 1] = '0'; } // handle target table const targetIsFixTable = targetTable === fixTableRef.current; const targetColumnsWidths = computeTableColumnsRightPositions(targetColumns); const {left: targetTableLeft} = targetTable.getBoundingClientRect(); const targetScrollLeft = targetTable.scrollLeft; const targetColumnIndex = targetColumnsWidths.findIndex(width => { // fix table has row number column return width - targetScrollLeft > mouseClientX - targetTableLeft - (targetIsFixTable ? rowNoColumnWidth : 0); }); let targetHeader, targetBody, targetGridTemplateColumns; if (sourceTable === targetTable) { targetHeader = sourceHeader; targetBody = sourceBody; targetGridTemplateColumns = sourceGridTemplateColumns; } else { targetHeader = targetTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-header"]')!; targetBody = targetTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-body"]')!; targetGridTemplateColumns = resetGridTemplateColumns({ element: targetHeader, columns: targetColumns, isFixTable: targetIsFixTable }); } if (targetColumnIndex === -1) { // console.group(); // console.info('target is fix table:', targetIsFixTable); // console.info('mouse client x:', mouseClientX, ', target scroll left:', targetScrollLeft); // console.info('fix table left:', fixTableRef.current!.getBoundingClientRect().left); // console.info('data table left:', dataTableRef.current!.getBoundingClientRect().left); // console.info('column widths:', targetColumnsWidths.join(', ')); // console.groupEnd(); // 2 scenarios here: if (targetIsFixTable) { // 1. in fix table, dragging column is from data table, and mouse is at right of all fixed columns. // the tricky scenario as below, // when a column is from data table, move into fix table, and now it is at tail of last column of fix table (mouse client x in right half of fix table column), // physically, the mouse client x is still in fix table (sometimes it is moved to data table, catch by above logic branch, not in this discussion), // and in repaint function call, even the last column right position is less than mouse client x, // then the target column cannot be found, the undefined error raised in repaint function call. // root cause of this scenario is table width must be resized when a dragging column move in and out, a column placeholder is simulated for reminding current situation. // for fix this, it will be treated same as dragging column still in fix table, as last column. targetGridTemplateColumns[(targetColumns.length + 1) * 2] = `${pickedColumn.width}px`; } else { // 2. in data table, mouse is at right of all columns. targetGridTemplateColumns[targetColumns.length * 2 + 1] = `${pickedColumn.width}px`; } } else { const targetColumnRightX = targetColumnsWidths[targetColumnIndex]; const targetColumnLeftX = targetColumnRightX - targetColumns[targetColumnIndex].width; const targetColumnCenterX = (targetColumnRightX + targetColumnLeftX) / 2; if (mouseClientX - targetTableLeft > targetColumnCenterX - targetScrollLeft) { // drag column after this targetGridTemplateColumns[(targetColumnIndex + 1) * 2 + (targetIsFixTable ? 2 : 0)] = `${pickedColumn.width}px`; } else { // drag column before this targetGridTemplateColumns[(targetColumnIndex + 1) * 2 + (targetIsFixTable ? 2 : 0) - 2] = `${pickedColumn.width}px`; } } // repaint const isTableInside = sourceTable === targetTable; if (!isTableInside) { // ignore once when move column inside const newSourceGridTemplateColumns = sourceGridTemplateColumns.join(' '); sourceHeader.style.gridTemplateColumns = newSourceGridTemplateColumns; sourceBody.style.gridTemplateColumns = newSourceGridTemplateColumns; } const newTargetGridTemplateColumns = targetGridTemplateColumns.join(' '); targetHeader.style.gridTemplateColumns = newTargetGridTemplateColumns; targetBody.style.gridTemplateColumns = newTargetGridTemplateColumns; // move column from one table to another, should change fix table width and data table left. // even move inside table, since column might be move out and move in again, therefore compute width and left is required. let fixTableWidth; let fixTable; let dataTable; if (sourceIsFixTable) { // source from fix table fixTableWidth = sourceGridTemplateColumns.map(width => parseInt(width)).reduce((total, width) => total + width, 0); if (isTableInside) { // target to fix table fixTable = sourceTable; // reset data table since processing above is all about fix table dataTable = dataTableRef.current!; const dataTableHeader = dataTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-header"]')!; const dataTableBody = dataTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-body"]')!; const dataTableGridColumns = `0 ${columnDefs.data.map(column => `${column.width}px 0`).join(' ')} minmax(${FILLER_MIN_WIDTH}px, 1fr)`; dataTableHeader.style.gridTemplateColumns = dataTableGridColumns; dataTableBody.style.gridTemplateColumns = dataTableGridColumns; } else { // target to data table fixTable = sourceTable; dataTable = targetTable; } } else { // source from data table if (isTableInside) { // target to data table // reset fix table since processing above is all about data table fixTable = fixTableRef.current!; const fixTableHeader = fixTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-header"]')!; const fixTableBody = fixTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-body"]')!; const fixTableGridColumns = `0 ${rowNoColumnWidth}px 0 ${columnDefs.fixed.map(column => `${column.width}px 0`).join(' ')}`; fixTableHeader.style.gridTemplateColumns = fixTableGridColumns; fixTableBody.style.gridTemplateColumns = fixTableGridColumns; fixTableWidth = columnDefs.fixed.reduce((width, column) => width + column.width, rowNoColumnWidth); dataTable = sourceTable; } else { // target to fix table fixTableWidth = targetGridTemplateColumns.map(width => parseInt(width)).reduce((total, width) => total + width, 0); fixTable = targetTable; dataTable = sourceTable; } } fixTable.style.minWidth = 'unset'; fixTable.style.width = `${fixTableWidth}px`; dataTable.style.left = `${fixTableWidth}px`; dataTable.style.position = 'absolute'; dataTable.style.width = `calc(100% - ${fixTableWidth}px)`; }; const computeSourceAndTarget = (mouseClientX: number, column: DataColumnDef) => { const dataTable = dataTableRef.current!; const fixTable = fixTableRef.current!; const dataTableLeft = dataTable.getBoundingClientRect().left; let fromFixTable, toFixTable, sourceTable, sourceColumns, targetTable, targetColumns; if (columnDefs.data.includes(column)) { fromFixTable = false; sourceTable = dataTable; sourceColumns = columnDefs.data; } else { fromFixTable = true; sourceTable = fixTable; sourceColumns = columnDefs.fixed; } if (mouseClientX >= dataTableLeft) { toFixTable = false; targetTable = dataTable; targetColumns = columnDefs.data; } else { toFixTable = true; targetTable = fixTable; targetColumns = columnDefs.fixed; } return {fromFixTable, toFixTable, sourceTable, sourceColumns, targetTable, targetColumns}; }; const dragColumn = async (mouseClientX: number) => { if (!pickedColumn) { return; } const wrapper = wrapperRef.current!; const {left: wrapperLeft} = wrapper.getBoundingClientRect(); const movementX = mouseClientX - wrapperLeft - pickedColumn.offsetX; fire(GridEventTypes.ASK_DRAG_COLUMN_VISIBLE, (dragColumnVisible) => { if (!dragColumnVisible && Math.abs(movementX) <= DRAG_DEVIATION) { // start dragging when movement reach deviation return; } // table content should be selected since shade is not shown now, // force clear selection to avoid confusing window.getSelection()?.removeAllRanges(); fire(GridEventTypes.DRAG_COLUMN_STATE_CHANGED, { left: mouseClientX - wrapperLeft - pickedColumn.column.width / 2, movementX }); if (behavior !== Behavior.DRAGGING) { // auto select the dragging column, remove the current column selection const selection = selectionRef.current!.selection(); fire(GridEventTypes.SELECTION_CHANGED, selection.inFixTable, selection.row, -1); setBehavior(Behavior.DRAGGING); } if (!dragColumnVisible) { fire(GridEventTypes.DRAG_COLUMN_VISIBLE_CHANGED, true); } const { sourceTable, sourceColumns, targetTable, targetColumns } = computeSourceAndTarget(mouseClientX, pickedColumn.column); // repaint drag column placeholder repaintWhenDragging({ mouseClientX, sourceTable, sourceColumns, targetTable, targetColumns, pickedColumn: pickedColumn.column }); }); }; const onMouseMove = (event: MouseEvent<HTMLDivElement>) => { if (behavior === Behavior.RESIZING && pickedColumn) { resizeColumn(event.clientX); } else if ((behavior === Behavior.READY_TO_DRAG || behavior === Behavior.DRAGGING) && pickedColumn) { // noinspection JSIgnoredPromiseFromCall dragColumn(event.clientX); } else { // nothing decide yet, just manager cursor to remind user manageCursor({ table: findDataTable(event.target as HTMLElement), mouseClientX: event.clientX, mouseClientY: event.clientY, avoidResize: false }); } }; const prepareToDragColumn = (table: HTMLDivElement, mouseClientX: number) => { const isFixTable = table === fixTableRef.current; const wrapperLeft = wrapperRef.current!.getBoundingClientRect().left; const pickedColumn = findPickedColumnForDrag({ wrapperLeft, table, mouseClientX, columnDefs, isFixTable, rowNoColumnWidth }); setPickedColumn(pickedColumn); const {scrollTop} = table; const height = Math.min(table.clientHeight, HEADER_HEIGHT + data.data.length * ROW_HEIGHT); const startRowIndex = Math.floor(scrollTop / ROW_HEIGHT); const endRowIndex = startRowIndex + Math.ceil((height - HEADER_HEIGHT) / ROW_HEIGHT + 2); fire(GridEventTypes.DRAG_COLUMN_STATE_CHANGED, { height, startRowIndex, endRowIndex, firstRowOffsetY: scrollTop % ROW_HEIGHT, movementX: 0 }); setBehavior(Behavior.READY_TO_DRAG); }; const prepareToResizeColumn = (table: HTMLDivElement, mouseClientX: number) => { setPickedColumn(findPickedColumnForResize({ wrapperLeft: wrapperRef.current!.getBoundingClientRect().left, table, mouseClientX, columnDefs, isFixTable: table === fixTableRef.current, rowNoColumnWidth })); setBehavior(Behavior.RESIZING); }; const onMouseDown = (event: MouseEvent<HTMLDivElement>) => { if (behavior === Behavior.CAN_RESIZE) { // start to resize column prepareToResizeColumn(findDataTable(event.target as HTMLElement)!, event.clientX); } else if (behavior === Behavior.PICK_COLUMN) { // start to resize column prepareToDragColumn(findDataTable(event.target as HTMLElement)!, event.clientX); } }; const releaseDragColumn = (mouseClientX: number) => { if (!pickedColumn) { return; } const dragColumn = pickedColumn.column; const {fromFixTable, toFixTable} = computeSourceAndTarget(mouseClientX, dragColumn); let sourceColumnIndex; if (fromFixTable) { sourceColumnIndex = columnDefs.fixed.indexOf(dragColumn); columnDefs.fixed.splice(sourceColumnIndex, 1); } else { sourceColumnIndex = columnDefs.data.indexOf(dragColumn); columnDefs.data.splice(sourceColumnIndex, 1); } const fixTable = fixTableRef.current!; const dataTable = dataTableRef.current!; let targetColumnIndex; // detect the move to index, convert the placeholder index to column index if (toFixTable) { // in grid template columns css, placeholder index is 2, 4, 6, ..., column length * 2 + 2 const fixTableHeader = fixTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-header"]')!; const fixTableBody = fixTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-body"]')!; const placeholderWidths = fixTableHeader.style.gridTemplateColumns.split(' ') .filter((width, index) => index >= 2 && index % 2 === 0).map(width => parseInt(width)); const placeholderIndex = placeholderWidths.findIndex(width => width !== 0); if (fromFixTable) { // if drag column is from fix table, it depends on the relationship between source column index and target column index if (placeholderIndex === sourceColumnIndex || placeholderIndex - 1 === sourceColumnIndex) { // actually doesn't change columns order targetColumnIndex = sourceColumnIndex; } else if (placeholderIndex < sourceColumnIndex) { // move backward, use placeholder index as target column index targetColumnIndex = placeholderIndex; } else { // move forward, use placeholder index subtract 1 targetColumnIndex = placeholderIndex - 1; } } else { // otherwise drag column is from data table, simply use placeholder index as target column index targetColumnIndex = placeholderIndex; } columnDefs.fixed.splice(targetColumnIndex, 0, dragColumn); const fixTableGridColumns = `0 ${rowNoColumnWidth}px 0 ${columnDefs.fixed.map(column => `${column.width}px 0`).join(' ')}`; fixTableHeader.style.gridTemplateColumns = fixTableGridColumns; fixTableBody.style.gridTemplateColumns = fixTableGridColumns; } else { // in grid template columns css, placeholder index is 0, 2, 4, 6, ..., column length * 2 const dataTableHeader = dataTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-header"]')!; const dataTableBody = dataTable.querySelector<HTMLDivElement>('div[data-widget="dataset-grid-body"]')!; const placeholderWidths = dataTableHeader.style.gridTemplateColumns.split(' ') .filter((width, index) => index % 2 === 0).map(width => parseInt(width)); const placeholderIndex = placeholderWidths.findIndex(width => width !== 0); if (fromFixTable) { // if drag column is from fix table, simply use placeholder index as target column index targetColumnIndex = placeholderIndex; } else { // otherwise, it depends on the relationship between source column index and target column index if (placeholderIndex === sourceColumnIndex || placeholderIndex - 1 === sourceColumnIndex) { // actually doesn't change columns order targetColumnIndex = sourceColumnIndex; } else if (placeholderIndex < sourceColumnIndex) { // move backward, use placeholder index as target column index targetColumnIndex = placeholderIndex; } else { // move forward, use placeholder index subtract 1 targetColumnIndex = placeholderIndex - 1; } } columnDefs.data.splice(targetColumnIndex, 0, dragColumn); const dataTableGridColumns = `0 ${columnDefs.data.map(column => `${column.width}px 0`).join(' ')} minmax(${FILLER_MIN_WIDTH}px, 1fr)`; dataTableHeader.style.gridTemplateColumns = dataTableGridColumns; dataTableBody.style.gridTemplateColumns = dataTableGridColumns; } // recover table styles fixTable.style.minWidth = `${columnDefs.fixed.reduce((width, column) => width + column.width, rowNoColumnWidth)}px`; fixTable.style.width = ''; dataTable.style.left = ''; dataTable.style.position = ''; dataTable.style.width = ''; setPickedColumn(null); fire(GridEventTypes.DRAG_COLUMN_VISIBLE_CHANGED, false); setBehavior(Behavior.NONE); const selection = selectionRef.current!.selection(); fire(GridEventTypes.SELECTION_CHANGED, toFixTable, selection.row, targetColumnIndex); }; const onMouseUp = (event: MouseEvent<HTMLDivElement>) => { if (behavior === Behavior.RESIZING) { // recover data table layout const dataTable = dataTableRef.current!; dataTable.style.left = ''; dataTable.style.position = ''; dataTable.style.width = ''; // always fire mouse up on resize shade, find resize table by state const resizeTable = columnDefs.fixed.some(c => c === pickedColumn?.column) ? fixTableRef.current : dataTableRef.current; // clear resize data setPickedColumn(null); // recover cursor manageCursor({ table: resizeTable, mouseClientX: event.clientX, mouseClientY: event.clientY, avoidResize: true }); } else if (behavior === Behavior.READY_TO_DRAG) { setPickedColumn(null); fire(GridEventTypes.DRAG_COLUMN_VISIBLE_CHANGED, false); setBehavior(Behavior.PICK_COLUMN); } else if (behavior === Behavior.DRAGGING) { releaseDragColumn(event.clientX); } }; const onMouseLeave = (event: MouseEvent<HTMLDivElement>) => { if (behavior === Behavior.RESIZING) { // recover data table layout const dataTable = dataTableRef.current!; dataTable.style.left = ''; dataTable.style.position = ''; dataTable.style.width = ''; setPickedColumn(null); setBehavior(Behavior.NONE); } else if (behavior === Behavior.READY_TO_DRAG) { setPickedColumn(null); fire(GridEventTypes.DRAG_COLUMN_VISIBLE_CHANGED, false); setBehavior(Behavior.PICK_COLUMN); } else if (behavior === Behavior.DRAGGING) { releaseDragColumn(event.clientX); } }; const onColumnFixChange = (column: DataColumnDef, fix: boolean) => { // defs must be synchronized to memory immediately, otherwise selection cannot compute positions correctly // according to this, here change the state, and call force update manually. if (fix) { // move leading columns and me from data columns to fix columns const index = columnDefs.data.indexOf(column); columnDefs.fixed = [...columnDefs.fixed, ...columnDefs.data.splice(0, index + 1)]; fire(GridEventTypes.FIX_COLUMN_CHANGED, fix, index + 1); forceUpdate(); } else { // move me and tailing columns from fix columns to data columns const index = columnDefs.fixed.indexOf(column); const count = columnDefs.fixed.length - index; columnDefs.data = [...columnDefs.fixed.splice(index), ...columnDefs.data]; fire(GridEventTypes.FIX_COLUMN_CHANGED, fix, count); forceUpdate(); } }; const onColumnSort = (column: DataColumnDef, asc: boolean) => { const index = column.index; if (asc && column.sort === ColumnSortBy.ASC) { return; } if (!asc && column.sort === ColumnSortBy.DESC) { return; } data.data.sort((r1, r2) => { let ret; const v1 = r1[index]; const v2 = r2[index]; if (v1 == null) { ret = -1; } else if (v2 == null) { ret = 1; } else if (typeof v1 === 'number' && typeof v2 === 'number') { ret = v1 - v2; } else if (typeof v1 === 'boolean' && typeof v2 === 'boolean') { ret = !v1 ? -1 : (!v2 ? 1 : 0); } else { ret = `${v1}`.toUpperCase().localeCompare(`${v2}`.toUpperCase()); } return asc ? ret : ret * -1; }); column.sort = asc ? ColumnSortBy.ASC : ColumnSortBy.DESC; columnDefs.fixed.filter(c => c !== column).forEach(c => c.sort = ColumnSortBy.NONE); columnDefs.data.filter(c => c !== column).forEach(c => c.sort = ColumnSortBy.NONE); forceUpdate(); }; return <GridWrapperContainer data-resize-state={behavior} onMouseMove={onMouseMove} onMouseDown={onMouseDown} onMouseUp={onMouseUp} onMouseLeave={onMouseLeave} ref={wrapperRef}> <Grid displayColumns={columnDefs.fixed} isFixTable={true} rowNoColumnWidth={rowNoColumnWidth} data={data} onColumnFixChange={onColumnFixChange} onColumnSort={onColumnSort} dragColumn={behavior === Behavior.DRAGGING ? pickedColumn?.column : (void 0)} languagesSupport={languagesSupport} ref={fixTableRef}/> <Grid displayColumns={columnDefs.data} isFixTable={false} rowNoColumnWidth={rowNoColumnWidth} data={data} onColumnFixChange={onColumnFixChange} onColumnSort={onColumnSort} dragColumn={behavior === Behavior.DRAGGING ? pickedColumn?.column : (void 0)} languagesSupport={languagesSupport} ref={dataTableRef}/> <GridSelection data={data} columnDefs={columnDefs} rowNoColumnWidth={rowNoColumnWidth} dataTableRef={dataTableRef} ref={selectionRef}/> <GridResizeShade visible={behavior === Behavior.RESIZING || behavior === Behavior.DRAGGING}/> <GridDragColumn data={data} column={pickedColumn?.column}/> <GridScrollShade wrapperRef={wrapperRef} dataTableRef={dataTableRef} visible={behavior === Behavior.DRAGGING}/> </GridWrapperContainer>; };
the_stack
module TDev.RT { //? Browse and review scripts from the bazaar //@ skill(3) export module Bazaar { //? Returns a user object for a specified user id //@ cachedAsync returns(User) export function user_of(id: string, r: ResumeCtx) { User.getJsonAsync(id).done(user => r.resumeVal((user && user.kind == "user") ? User.mk(id) : undefined), e => r.resumeVal(undefined)); } export function userIdAsync(rt:Runtime) : Promise { // : string if (!rt.requiresAuth()) return Promise.as(rt.getUserId()) return Cloud.authenticateAsync(lf("user identification")) .then(() => Cloud.getUserId()); } //? Returns the user object of the current user //@ returns(User) authAsync export function current_user(r: ResumeCtx) { userIdAsync(r.rt).done(userId => r.resumeVal(userId ? User.mk(userId) : undefined)); } export function cachedScore(rt: Runtime, score?: number): number { var currentScore = rt.datas["this"]["leaderboard_score"] || 0; if (score && score > currentScore) { rt.datas["this"]["leaderboard_score"] = score; currentScore = score; } return currentScore; } //? Gets the current score for the current script //@ async returns(number) //@ tandre hasPauseContinue //@ readsMutable export function leaderboard_score(r: ResumeCtx) // : number { var rt = r.rt; var currentScore = cachedScore(rt); var localScore = () => r.resumeVal(currentScore); if (!rt.currentScriptId || !Cloud.isOnline()) { localScore(); } else { Cloud.authenticateAsync(lf("leaderboard")) .done((authenticated: boolean) => { if (authenticated) { var url = Cloud.getPrivateApiUrl('me/leaderboardscored/' + rt.currentScriptId); var request = WebRequest.mk(url, undefined); request.sendAsync() .done((response: WebResponse) => { var curr = 0; var json = response.content_as_json(); if (json) curr = json.number('score'); // max with local score to avoid race in cloud r.resumeVal(cachedScore(rt, Math.max(currentScore, curr || 0))); }); } else { localScore(); } }); } } export function postScoreToOfficeMix(score : number, scriptId: string) { // in office mix, always send a score message if (Browser.webRunner || Browser.webAppImplicit) { var msg = JsonObject.wrap({ kind: "leaderboardScore__Send", data: { score: score, scriptId: scriptId } }); Web.post_message_to_parent(Cloud.config.rootUrl, msg, null); Web.post_message_to_parent("http://localhost:15669", msg, null); } } //? Posts the current game score to the script leaderboard //@ async //@ writesMutable export function post_leaderboard_score(score: number, r: ResumeCtx) //: void { var rt = r.rt; var currentScore = cachedScore(rt, score); if (!rt.currentScriptId || !Cloud.isOnline()) { r.resume(); } else { Bazaar.postScoreToOfficeMix(score, rt.currentScriptId); Cloud.authenticateAsync(lf("leaderboard")) .done((authenticated: boolean) => { if (authenticated) { var url = Cloud.getPrivateApiUrl(rt.currentScriptId + '/leaderboardscores'); var request = WebRequest.mk(url, undefined); request.set_method('post'); request.set_content_as_json(JsonObject.mk(JSON.stringify({ kind: "leaderboardscore", score: score || 0, userplatform: Browser.platformCaps }), Util.log)); request.sendAsync() .done((response: WebResponse) => { var json = response.content_as_json(); if (json) cachedScore(rt, json.number('score')) r.resume(); }); } }, e => { // something wrong happened, keep moving r.resume(); }); } } export function loadLeaderboardItemsAsync(striptId : string): Promise { // HTMLElement if (!striptId || !Cloud.isOnline()) return Promise.as([]); return Cloud.getPublicApiAsync(striptId + '/leaderboardscores?count=250') .then(leaderboards => { return leaderboards.items.map(item => { var userid = item.userid; var username = item.username; var userscore = item.score.toString(); var time = Util.timeSince(item.time); var imgDiv = div('leaderboard-img'); if (item.userhaspicture) imgDiv.style.backgroundImage = HTML.cssImage(Cloud.getPublicApiUrl(userid + "/picture?type=normal")) else imgDiv.innerHTML = TDev.Util.svgGravatar(userid); var scoreDiv = div('item leaderboard-item', [ imgDiv, div('leaderboards-score', userscore), div('leaderboard-center', [ div('item-title', username), div('item-subtle', time) ]) ]); return scoreDiv; }); }, e => { return []; }); } //? Posts the current game leaderboard to the wall //@ cachedAsync export function post_leaderboard_to_wall(r: ResumeCtx) //: void { // TODO this should be cached for page display var rt = r.rt; if (!rt.currentScriptId) { var curr = cachedScore(rt).toString(); var imgDiv = div('leaderboard-img'); imgDiv.innerHTML = TDev.Util.svgGravatar('me'); var leaderboardDiv = div('item leaderboard-item', [ imgDiv, div('leaderboards-score', curr), div('leaderboard-center', [ div('item-title', lf("Me")), div('item-subtle', lf("Publish your script to get a leaderboard available for all your users.")), ]) ]); r.rt.postBoxedHtml(leaderboardDiv, r.rt.current.pc); r.resume(); } else if (!Cloud.isOnline()) { var curr = cachedScore(rt).toString(); var imgDiv = div('leaderboard-img'); imgDiv.innerHTML = TDev.Util.svgGravatar('me'); var leaderboardDiv = div('item leaderboard-item', [ imgDiv, div('leaderboards-score', curr), div('leaderboard-center', [ div('item-title', lf("Me")), div('item-subtle', lf("Please connect to internet to load the leaderboards.")), ]) ]); r.rt.postBoxedHtml(leaderboardDiv, r.rt.current.pc); r.resume(); } else { r.progress(lf("Loading leaderboards...")); var leaderboardDiv = div(''); loadLeaderboardItemsAsync(rt.currentScriptId).done(els => { leaderboardDiv.setChildren(els); rt.postBoxedHtml(leaderboardDiv, r.rt.current.pc); r.resume(); }, e => { rt.postBoxedText(lf("Oops, could not get the leaderboards. Please check your internet connection."), r.rt.current.pc); r.resume(); }); } } //? three-way merge script texts. Debug only: for testing. //@ dbgOnly export function merge3(O: string, A: string, B: string): string { var t1 = (<any>TDev).AST.Parser.parseScript(O); var t2 = (<any>TDev).AST.Parser.parseScript(A); var t3 = (<any>TDev).AST.Parser.parseScript(B); (<any>TDev).AST.TypeChecker.tcApp(t1); (<any>TDev).AST.TypeChecker.tcApp(t2); (<any>TDev).AST.TypeChecker.tcApp(t3); (<any>TDev).TheEditor.initIds(t1); (<any>TDev).TheEditor.initIds(t2); (<any>TDev).TheEditor.initIds(t3); var merged = (<any>TDev).AST.Merge.merge3(t1, t2, t3); return merged.serialize(); } //? Launches the bazaar. //@ obsolete export function open(): void { // obsolete, does nothing } //? Opens the review page for the current script //@ obsolete export function open_review(): void { // obsolete, does nothing } //? Opens the leaderboard for the current script //@ obsolete export function open_leaderboard(r : ResumeCtx): void { post_leaderboard_to_wall(r); } //? Returns an identifier of either the top-level script or the current library //@ [which].deflStrings("top", "current") export function script_id(which:string, s:IStackFrame) : string { if (which == "top") return s.libs.topScriptId; if (which == "current") return s.libs.scriptId; return undefined; } //? Asks the user to pick a script and return its identifier //@ [mode].deflStrings("read", "write", "read-write") //@ returns(string) uiAsync export function pick_script(mode:string, message:string, r: ResumeCtx) { r.rt.host.pickScriptAsync(mode, message).done((id) => { r.resumeVal(id); }) } //? Saves given Abstract Syntax Tree as a script //@ uiAsync export function save_ast(id:string, script:JsonObject, r: ResumeCtx) { r.rt.host.saveAstAsync(id, script.value()).done((id) => { r.resume() }) } //? Returns the Abstract Syntax Tree JSON object for specified script //@ [id].deflExpr('bazaar->script_id("current")') //@ returns(JsonObject) uiAsync export function ast_of(id:string, r: ResumeCtx) { r.rt.host.astOfAsync(id).done((j) => { if (!j) r.resumeVal(undefined); else r.resumeVal(JsonObject.wrap(j)); }) } // returns the app store id if compiled export var storeidAsync = (): Promise => { // of string var host : any = (<any>window).touchDevelopHost; if (host) { Util.log("using touchdevelop host"); var id = host.storeid()||""; Util.log("storeid: " + id); return Promise.as(id); } return Promise.as(""); }; } }
the_stack
import chalk from 'chalk'; import { isEmpty, difference } from 'lodash'; import ora = require('ora'); import { ValidConfigOptions } from '../options/options'; import { HandledError } from '../services/HandledError'; import { exec } from '../services/child-process-promisified'; import { getRepoPath } from '../services/env'; import { cherrypick, createBackportBranch, deleteBackportBranch, pushBackportBranch, setCommitAuthor, getUnstagedFiles, commitChanges, getConflictingFiles, getRepoForkOwner, fetchBranch, ConflictingFiles, getIsCommitInBranch, } from '../services/git'; import { getFirstLine, getShortSha } from '../services/github/commitFormatters'; import { addAssigneesToPullRequest } from '../services/github/v3/addAssigneesToPullRequest'; import { addLabelsToPullRequest } from '../services/github/v3/addLabelsToPullRequest'; import { addReviewersToPullRequest } from '../services/github/v3/addReviewersToPullRequest'; import { createPullRequest, getTitle, getPullRequestBody, PullRequestPayload, } from '../services/github/v3/createPullRequest'; import { enablePullRequestAutoMerge } from '../services/github/v4/enablePullRequestAutoMerge'; import { fetchCommitsByAuthor } from '../services/github/v4/fetchCommits/fetchCommitsByAuthor'; import { consoleLog, logger } from '../services/logger'; import { confirmPrompt } from '../services/prompts'; import { sequentially } from '../services/sequentially'; import { Commit } from '../services/sourceCommit/parseSourceCommit'; export async function cherrypickAndCreateTargetPullRequest({ options, commits, targetBranch, }: { options: ValidConfigOptions; commits: Commit[]; targetBranch: string; }): Promise<{ url: string; number: number; didUpdate: boolean; }> { const backportBranch = getBackportBranchName(targetBranch, commits); const repoForkOwner = getRepoForkOwner(options); consoleLog(`\n${chalk.bold(`Backporting to ${targetBranch}:`)}`); const prPayload: PullRequestPayload = { owner: options.repoOwner, repo: options.repoName, title: getTitle({ options, commits, targetBranch }), body: getPullRequestBody({ options, commits, targetBranch }), head: `${repoForkOwner}:${backportBranch}`, // eg. sqren:backport/7.x/pr-75007 base: targetBranch, // eg. 7.x }; const targetPullRequest = await backportViaFilesystem({ options, prPayload, targetBranch, backportBranch, commits, }); // add assignees to target pull request if (options.assignees.length > 0) { await addAssigneesToPullRequest( options, targetPullRequest.number, options.assignees ); } // add reviewers to target pull request if (options.reviewers.length > 0) { await addReviewersToPullRequest( options, targetPullRequest.number, options.reviewers ); } // add labels to target pull request if (options.targetPRLabels.length > 0) { await addLabelsToPullRequest( options, targetPullRequest.number, options.targetPRLabels ); } // make PR auto mergable if (options.autoMerge) { await enablePullRequestAutoMerge(options, targetPullRequest.number); } // add labels to source pull requests if (options.sourcePRLabels.length > 0) { const promises = commits.map((commit) => { if (commit.pullNumber) { return addLabelsToPullRequest( options, commit.pullNumber, options.sourcePRLabels ); } }); await Promise.all(promises); } consoleLog(`View pull request: ${targetPullRequest.url}`); return targetPullRequest; } async function backportViaFilesystem({ options, prPayload, commits, targetBranch, backportBranch, }: { options: ValidConfigOptions; prPayload: PullRequestPayload; commits: Commit[]; targetBranch: string; backportBranch: string; }) { logger.info('Backporting via filesystem'); await createBackportBranch({ options, targetBranch, backportBranch }); await sequentially(commits, (commit) => waitForCherrypick(options, commit, targetBranch) ); if (options.resetAuthor) { await setCommitAuthor(options, options.username); } await pushBackportBranch({ options, backportBranch }); await deleteBackportBranch({ options, backportBranch }); return createPullRequest({ options, prPayload }); } // when the user is facing a git conflict we should help them understand // why the conflict occurs. In many cases it's because one or more commits haven't been backported yet export async function getCommitsWithoutBackports({ options, commit, targetBranch, conflictingFiles, }: { options: ValidConfigOptions; commit: Commit; targetBranch: string; conflictingFiles: string[]; }) { const commitsInConflictingPaths = await fetchCommitsByAuthor({ ...options, all: true, commitPaths: conflictingFiles, }); return ( await Promise.all( commitsInConflictingPaths .filter((c) => { // exclude the commit we are currently trying to backport if (c.sha === commit.sha) { return false; } // exclude commits that are newer than the commit we are trying to backport if (c.committedDate > commit.committedDate) { return false; } const alreadyBackported = c.expectedTargetPullRequests.some( (pr) => pr.branch === targetBranch && pr.state === 'MERGED' ); if (alreadyBackported) { return false; } return true; }) .slice(0, 10) // limit to max 10 commits .map(async (c) => { const isCommitInBranch = await getIsCommitInBranch(options, c.sha); return { c, isCommitInBranch }; }) ) ) .filter(({ isCommitInBranch }) => !isCommitInBranch) .map(({ c }) => { // get pull request for the target branch (if it exists) const unmergedPr = c.expectedTargetPullRequests.find( (pr) => pr.branch === targetBranch ); const formatted = ` - ${getFirstLine(c.originalMessage)}${ unmergedPr?.state === 'OPEN' ? chalk.gray(' (backport pending)') : '' }${c.pullUrl ? `\n ${c.pullUrl}` : ''}`; return { formatted, commit: c }; }); } /* * Returns the name of the backport branch without remote name * * Examples: * For a single PR: `backport/7.x/pr-1234` * For a single commit: `backport/7.x/commit-abcdef` * For multiple: `backport/7.x/pr-1234_commit-abcdef` */ export function getBackportBranchName(targetBranch: string, commits: Commit[]) { const refValues = commits .map((commit) => commit.pullNumber ? `pr-${commit.pullNumber}` : `commit-${getShortSha(commit.sha)}` ) .join('_') .slice(0, 200); return `backport/${targetBranch}/${refValues}`; } async function waitForCherrypick( options: ValidConfigOptions, commit: Commit, targetBranch: string ) { const spinnerText = `Cherry-picking: ${chalk.greenBright( getFirstLine(commit.originalMessage) )}`; const cherrypickSpinner = ora(spinnerText).start(); let conflictingFiles: ConflictingFiles; let unstagedFiles: string[]; let needsResolving: boolean; try { await fetchBranch(options, commit.sourceBranch); ({ conflictingFiles, unstagedFiles, needsResolving } = await cherrypick( options, commit.sha )); // no conflicts encountered if (!needsResolving) { cherrypickSpinner.succeed(); return; } // cherrypick failed due to conflicts cherrypickSpinner.fail(); } catch (e) { cherrypickSpinner.fail(); throw e; } // resolve conflicts automatically if (options.autoFixConflicts) { const autoResolveSpinner = ora( 'Attempting to resolve conflicts automatically' ).start(); const repoPath = getRepoPath(options); const didAutoFix = await options.autoFixConflicts({ files: conflictingFiles.map((f) => f.absolute), directory: repoPath, logger, targetBranch, }); // conflicts were automatically resolved if (didAutoFix) { autoResolveSpinner.succeed(); return; } autoResolveSpinner.fail(); } const commitsWithoutBackports = await getCommitsWithoutBackports({ options, commit, targetBranch, conflictingFiles: conflictingFiles.map((f) => f.relative).slice(0, 50), }); consoleLog( chalk.bold('\nThe commit could not be backported due to conflicts\n') ); if (commitsWithoutBackports.length > 0) { consoleLog( chalk.italic( `Hint: Before fixing the conflicts manually you should consider backporting the following commits to "${targetBranch}":` ) ); consoleLog( `${commitsWithoutBackports.map((c) => c.formatted).join('\n')}\n\n` ); } if (options.ci) { throw new HandledError( `Commit could not be cherrypicked due to conflicts`, { type: 'commitsWithoutBackports', commitsWithoutBackports, } ); } /* * Commit could not be cleanly cherrypicked: Initiating conflict resolution */ if (options.editor) { const repoPath = getRepoPath(options); await exec(`${options.editor} ${repoPath}`, {}); } // list files with conflict markers + unstaged files and require user to resolve them await listConflictingAndUnstagedFiles({ retries: 0, options, conflictingFiles: conflictingFiles.map((f) => f.absolute), unstagedFiles, }); // Conflicts should be resolved and files staged at this point const stagingSpinner = ora(`Finalizing cherrypick`).start(); try { // Run `git commit` await commitChanges(commit, options); stagingSpinner.succeed(); } catch (e) { stagingSpinner.fail(); throw e; } } async function listConflictingAndUnstagedFiles({ retries, options, conflictingFiles, unstagedFiles, }: { retries: number; options: ValidConfigOptions; conflictingFiles: string[]; unstagedFiles: string[]; }): Promise<void> { const hasUnstagedFiles = !isEmpty( difference(unstagedFiles, conflictingFiles) ); const hasConflictingFiles = !isEmpty(conflictingFiles); if (!hasConflictingFiles && !hasUnstagedFiles) { return; } // add divider between prompts if (retries > 0) { consoleLog('\n----------------------------------------\n'); } const header = chalk.reset(`Fix the following conflicts manually:`); // show conflict section if there are conflicting files const conflictSection = hasConflictingFiles ? `Conflicting files:\n${chalk.reset( conflictingFiles.map((file) => ` - ${file}`).join('\n') )}` : ''; const unstagedSection = hasUnstagedFiles ? `Unstaged files:\n${chalk.reset( unstagedFiles.map((file) => ` - ${file}`).join('\n') )}` : ''; const res = await confirmPrompt(`${header} ${conflictSection} ${unstagedSection} Press ENTER when the conflicts are resolved and files are staged`); if (!res) { throw new HandledError('Aborted'); } const MAX_RETRIES = 100; if (retries++ > MAX_RETRIES) { throw new Error(`Maximum number of retries (${MAX_RETRIES}) exceeded`); } const [_conflictingFiles, _unstagedFiles] = await Promise.all([ getConflictingFiles(options), getUnstagedFiles(options), ]); await listConflictingAndUnstagedFiles({ retries, options, conflictingFiles: _conflictingFiles.map((file) => file.absolute), unstagedFiles: _unstagedFiles, }); }
the_stack
import { Observable } from 'rxjs'; import { ConfirmAuBecsDebitPaymentData, ConfirmAuBecsDebitSetupData, ConfirmBancontactPaymentData, ConfirmBancontactPaymentOptions, ConfirmCardPaymentData, ConfirmCardPaymentOptions, ConfirmEpsPaymentData, ConfirmEpsPaymentOptions, ConfirmFpxPaymentData, ConfirmFpxPaymentOptions, ConfirmGiropayPaymentData, ConfirmGiropayPaymentOptions, ConfirmIdealPaymentData, ConfirmIdealPaymentOptions, ConfirmP24PaymentData, ConfirmP24PaymentOptions, ConfirmCardSetupData, ConfirmCardSetupOptions, ConfirmSepaDebitPaymentData, ConfirmSepaDebitSetupData, CreatePaymentMethodData, CreateSourceData, CreateTokenIbanData, CreateTokenCardData, CreateTokenPiiData, CreateTokenBankAccountData, PaymentIntent, PaymentMethod, PaymentRequest, PaymentRequestOptions, RedirectToCheckoutOptions, RetrieveSourceParam, SetupIntent, Stripe, StripeCardElement, StripeCardNumberElement, StripeCardCvcElement, StripeElements, StripeElementsOptions, StripeElement, StripeError, StripeIbanElement, Source, Token, TokenCreateParams, ConfirmAcssDebitPaymentData, ConfirmAcssDebitPaymentOptions, ConfirmAfterpayClearpayPaymentData, ConfirmAfterpayClearpayPaymentOptions, ConfirmAlipayPaymentData, ConfirmGrabPayPaymentData, ConfirmGrabPayPaymentOptions, ConfirmKlarnaPaymentData, ConfirmKlarnaPaymentOptions, ConfirmOxxoPaymentData, ConfirmOxxoPaymentOptions, ConfirmSofortPaymentData, ConfirmWechatPayPaymentData, ConfirmWechatPayPaymentOptions, VerifyMicrodepositsForPaymentData, ConfirmAcssDebitSetupData, ConfirmAcssDebitSetupOptions, ConfirmBacsDebitSetupData, ConfirmBancontactSetupData, ConfirmIdealSetupData, ConfirmSofortSetupData, VerifyMicrodepositsForSetupData, ConfirmAlipayPaymentOptions, VerificationSessionResult, ConfirmPayPalPaymentData, ConfirmPayPalSetupData, ConfirmPaymentData, ConfirmAffirmPaymentData, ConfirmAffirmPaymentOptions, ConfirmPromptPayPaymentData, ConfirmPromptPayPaymentOptions, ConfirmPayNowPaymentData, ConfirmPayNowPaymentOptions, ConfirmCustomerBalancePaymentData, ConfirmCustomerBalancePaymentOptions } from '@stripe/stripe-js'; export interface StripeServiceInterface { getInstance(): Stripe | undefined; elements(options?: StripeElementsOptions): Observable<StripeElements>; redirectToCheckout( options?: RedirectToCheckoutOptions ): Observable<never | { error: StripeError }>; confirmPayment(options: { elements: StripeElements; confirmParams?: Partial<ConfirmPaymentData>; redirect: 'if_required'; }): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmPayment(options: { elements: StripeElements; confirmParams: ConfirmPaymentData; redirect?: 'always'; }): Observable<never | {error: StripeError}>; confirmAcssDebitPayment( clientSecret: string, data?: ConfirmAcssDebitPaymentData, options?: ConfirmAcssDebitPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmAlipayPayment( clientSecret: string, data?: ConfirmAlipayPaymentData, options?: ConfirmAlipayPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmAuBecsDebitPayment( clientSecret: string, data?: ConfirmAuBecsDebitPaymentData ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmBancontactPayment( clientSecret: string, data?: ConfirmBancontactPaymentData, options?: ConfirmBancontactPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmCardPayment( clientSecret: string, data?: ConfirmCardPaymentData, options?: ConfirmCardPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmCustomerBalancePayment( clientSecret: string, data?: ConfirmCustomerBalancePaymentData, options?: ConfirmCustomerBalancePaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmEpsPayment( clientSecret: string, data?: ConfirmEpsPaymentData, options?: ConfirmEpsPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmFpxPayment( clientSecret: string, data?: ConfirmFpxPaymentData, options?: ConfirmFpxPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmGiropayPayment( clientSecret: string, data?: ConfirmGiropayPaymentData, options?: ConfirmGiropayPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmGrabPayPayment( clientSecret: string, data?: ConfirmGrabPayPaymentData, options?: ConfirmGrabPayPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmIdealPayment( clientSecret: string, data?: ConfirmIdealPaymentData, options?: ConfirmIdealPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmKlarnaPayment( clientSecret: string, data?: ConfirmKlarnaPaymentData, options?: ConfirmKlarnaPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmOxxoPayment( clientSecret: string, data?: ConfirmOxxoPaymentData, options?: ConfirmOxxoPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmP24Payment( clientSecret: string, data?: ConfirmP24PaymentData, options?: ConfirmP24PaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmPayNowPayment( clientSecret: string, data?: ConfirmPayNowPaymentData, options?: ConfirmPayNowPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmPayPalPayment( clientSecret: string, data?: ConfirmPayPalPaymentData ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmPromptPayPayment( clientSecret: string, data?: ConfirmPromptPayPaymentData, options?: ConfirmPromptPayPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmSepaDebitPayment( clientSecret: string, data?: ConfirmSepaDebitPaymentData ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmSofortPayment( clientSecret: string, data?: ConfirmSofortPaymentData ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmWechatPayPayment( clientSecret: string, data?: ConfirmWechatPayPaymentData, options?: ConfirmWechatPayPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; handleCardAction( clientSecret: string ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; verifyMicrodepositsForPayment( clientSecret: string, data?: VerifyMicrodepositsForPaymentData ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; createPaymentMethod( paymentMethodData: CreatePaymentMethodData ): Observable<{ paymentMethod?: PaymentMethod; error?: StripeError; }>; retrievePaymentIntent( clientSecret: string ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmSetup(options: { elements: StripeElements; confirmParams?: Partial<ConfirmPaymentData>; redirect: 'if_required'; }): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; confirmSetup(options: { elements: StripeElements; confirmParams: ConfirmPaymentData; redirect?: 'always'; }): Observable<never | { error: StripeError }>; confirmAcssDebitSetup( clientSecret: string, data?: ConfirmAcssDebitSetupData, options?: ConfirmAcssDebitSetupOptions ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; confirmAuBecsDebitSetup( clientSecret: string, data?: ConfirmAuBecsDebitSetupData ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; confirmBacsDebitSetup( clientSecret: string, data?: ConfirmBacsDebitSetupData ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; confirmBancontactSetup( clientSecret: string, data?: ConfirmBancontactSetupData ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; confirmCardSetup( clientSecret: string, data?: ConfirmCardSetupData, options?: ConfirmCardSetupOptions ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; confirmIdealSetup( clientSecret: string, data?: ConfirmIdealSetupData ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; confirmPayPalSetup( clientSecret: string, data?: ConfirmPayPalSetupData ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; confirmSepaDebitSetup( clientSecret: string, data?: ConfirmSepaDebitSetupData ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; confirmSofortSetup( clientSecret: string, data?: ConfirmSofortSetupData ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; confirmAffirmPayment( clientSecret: string, data?: ConfirmAffirmPaymentData, options?: ConfirmAffirmPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; confirmAfterpayClearpayPayment( clientSecret: string, data?: ConfirmAfterpayClearpayPaymentData, options?: ConfirmAfterpayClearpayPaymentOptions ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; verifyMicrodepositsForSetup( clientSecret: string, data?: VerifyMicrodepositsForSetupData ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; retrieveSetupIntent( clientSecret: string ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; paymentRequest(options: PaymentRequestOptions): PaymentRequest | undefined; createToken( tokenType: StripeIbanElement, data: CreateTokenIbanData ): Observable<{ token?: Token; error?: StripeError }>; createToken( tokenType: StripeCardElement | StripeCardNumberElement, data?: CreateTokenCardData ): Observable<{ token?: Token; error?: StripeError }>; createToken( tokenType: 'pii', data: CreateTokenPiiData ): Observable<{ token?: Token; error?: StripeError }>; createToken( tokenType: 'bank_account', data: CreateTokenBankAccountData ): Observable<{ token?: Token; error?: StripeError }>; createToken( tokenType: 'cvc_update', element?: StripeCardCvcElement ): Observable<{ token?: Token; error?: StripeError }>; createToken( tokenType: 'account', data: TokenCreateParams.Account ): Observable<{ token?: Token; error?: StripeError }>; createToken( tokenType: 'person', data: TokenCreateParams.Person ): Observable<{ token?: Token; error?: StripeError }>; createSource( element: StripeElement, sourceData: CreateSourceData ): Observable<{ source?: Source; error?: StripeError }>; createSource( sourceData: CreateSourceData ): Observable<{ source?: Source; error?: StripeError }>; retrieveSource( source: RetrieveSourceParam ): Observable<{ source?: Source; error?: StripeError }>; verifyIdentity(clientSecret: string): Observable<VerificationSessionResult>; /** * @deprecated */ handleCardPayment( clientSecret: string, element?, data? ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; /** * @deprecated */ confirmPaymentIntent( clientSecret: string, element?, data? ): Observable<{ paymentIntent?: PaymentIntent; error?: StripeError; }>; /** * @deprecated */ handleCardSetup( clientSecret: string, element?, data? ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; /** * @deprecated */ confirmSetupIntent( clientSecret: string, element?, data? ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; /** * @deprecated */ handleFpxPayment( clientSecret: string, element?, data? ): Observable<{ setupIntent?: SetupIntent; error?: StripeError; }>; }
the_stack
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'; import Mixin from './../Mixin'; import HeaderType from '@/pages/datamart/common/components/HeaderType.vue'; import alertConvergenceForm from '@/pages/dmonitorCenter/components/convergenceForm/alertConvergenceForm.vue'; import alertTriggerForm from '@/pages/dmonitorCenter/components/convergenceForm/alertTriggerForm.vue'; import receiverForm from '@/pages/dmonitorCenter/components/notifyForm/receiverForm.vue'; import RuleContentConfig from './RuleContentConfig'; import EventSelect from './EventSelect.vue'; import RuleModel from './RuleModel'; import NoData from '@/pages/datamart/DataDict/components/children/chartComponents/NoData.vue'; // api请求函数 import { queryQualityRuleFunc, queryQualityRuleIndex, queryQualityRuleTemplates, createQualityRules, updateQualityRules, getAuditEventTemp, getDataQualityEventTypes, getNotifyWayList, } from '@/pages/datamart/Api/DataQuality'; // 数据接口 import { IQualityRuleFunc, IQualityRuleIndex, IQualityRuleTemplate, IRuleConfigFields, IAuditEventTemp, IRuleFuncData, IRuleIndexData, IRuleTemplateData, IAuditEventTempData, INotifyWayList, INotifyWayData, } from '@/pages/datamart/InterFace/DataQuality'; import { BKHttpResponse } from '@/common/js/BKHttpResponse'; import { showMsg } from '@/common/js/util'; @Component({ mixins: [Mixin], components: { HeaderType, alertConvergenceForm, alertTriggerForm, receiverForm, RuleContentConfig, EventSelect, RuleModel, NoData, }, }) export default class QualityRuleConfig extends Vue { isShowEventAdvance = false; isEdit = true; isShowAdvance = false; isReceiverLoading = false; isShowDropContent = false; // 区分创建规则和更新规则 isCreated = false; isCoveredConfig = false; isChecking = false; isRuleTemplateLoading = false; isRuleIndexLoading = false; isRuleFuncLoading = false; isShowRuleModel = false; isRefresh = true; isShow = false; // 规则弹窗是否展示 isShowTableSelect = false; // 当聚焦时,显示表格 eventType = 'data_quality'; modelLimitMetrics: string[] = []; ruleFuncList: IRuleFuncData[] = []; ruleIndexList: IRuleIndexData[] = []; ruleTemplateList: IRuleTemplateData[] = []; auditEventTempList: IAuditEventTempData[] = []; receivers: string[] = []; roles = [ { objectClass: 'project', scopeId: this.$route.query.project_id, }, ]; eventTypeList = [ { id: 'data_quality', name: this.$t('质量事件'), }, ]; eventPolarityList = [ { id: 'positive', name: this.$t('正向'), }, { id: 'negative', name: this.$t('负向'), }, { id: 'neutral', name: this.$t('中性'), }, ]; influenceLevelList = [ { id: 'pubblic', name: this.$t('公开'), }, { id: 'private', name: this.$t('私有'), }, { id: 'confidential', name: this.$t('机密'), }, ]; ruleContent = ''; formData: IRuleConfigFields = { data_set_id: '', rule_name: '', rule_description: '', rule_template_id: '', rule_config: [ { metric: { metric_type: '', metric_name: '', }, function: '', constant: { constant_type: 'float', constant_value: 0, }, operation: 'and', }, ], event_name: '', event_alias: '', event_description: '', event_type: 'data_quality', event_sub_type: '', event_polarity: 'neutral', event_currency: '300', sensitivity: 'private', event_detail_template: '', notify_ways: [], receivers: [], // 表单中告警接收人 convergence_config: { duration: 1, alert_threshold: 1, mask_time: 1, }, rule_id: '', audit_task_status: '', rule_config_alias: '', }; userList = []; rules: Record<string, any> = { rule_name: [ { required: true, message: '必填项', trigger: 'blur', }, ], rule_template_id: [ { required: true, message: '必填项', trigger: 'blur', }, ], event_name: [ { required: true, message: '必填项', trigger: 'blur', }, ], event_alias: [ { required: true, message: '必填项', trigger: 'blur', }, ], event_description: [ { required: true, message: '必填项', trigger: 'blur', }, ], event_polarity: [ { required: true, message: '必填项', trigger: 'blur', }, ], event_currency: [ { required: true, message: '必填项', trigger: 'blur', }, ], sensitivity: [ { required: true, message: '必填项', trigger: 'blur', }, ], event_detail_template: [ { required: true, message: '必填项', trigger: 'blur', }, ], notify_ways: [], receivers: [ { required: true, message: '必填项', trigger: 'blur', }, { validator: function (val: []) { return val.length >= 1; }, message: '请选择接收人', trigger: 'blur', }, ], convergence_config: [ { required: true, message: '必填项', trigger: 'blur', }, { validator: function (val: {}) { return Object.values(val).every(item => item); }, message: '请填写收敛策略', trigger: 'blur', }, ], rule_config: [ { required: true, message: '必填项', trigger: 'blur', }, { validator: this.validatorRuleContent(), message: '请填写规则内容', trigger: 'blur', }, ], }; alertConfigInfo: any = { trigger_config: { duration: 1, alert_threshold: 1, }, convergence_config: { mask_time: 60, }, receivers: [], }; isNotifyLoading = false; isDropdownShow = false; // textarea组件光标位置 selectionStart = 0; notifyWays: Array<INotifyWayData> = [ { description: '', notifyWayAlias: '', active: false, notifyWay: '', notifyWayName: '', icon: '', }, ]; // 任务处于运行状态,禁止编辑 get isAllDisabled() { return !this.isEdit; } // 统一从store获取user信息 get bkUser() { return this.$store.getters.getUserName; } /** * onUserNameChange * @param name */ @Watch('bkUser', { immediate: true }) onUserNameChange(name: string) { // 新建规则配置时,默认设置自己为告警接收人 if (!this.isCreated) { this.formData.receivers = [name]; this.receivers = [name]; } } /** * onReceiversChange * @param val */ @Watch('receivers', { immediate: true }) onReceiversChange(val: []) { this.formData.receivers = val; } // alert信息变化时,更新表单 @Watch('alertConfigInfo', { immediate: true, deep: true }) onAlertConfigInfoChange() { const { duration, alert_threshold } = this.alertConfigInfo.trigger_config; this.formData.convergence_config.duration = duration; this.formData.convergence_config.alert_threshold = alert_threshold; this.formData.convergence_config.mask_time = this.alertConfigInfo.convergence_config.mask_time; } /** * mounted */ mounted() { this.queryQualityRuleFunc(); this.queryQualityRuleIndex(); this.queryQualityRuleTemplates(); this.getAuditEventTemp(); this.getProjectMember(); this.getDataQualityEventTypes(); this.getNotifyWayList(); } // 获取数据平台支持的所有告警通知方式 getNotifyWayList() { this.isNotifyLoading = true; getNotifyWayList().then(res => { const instance = new BKHttpResponse<INotifyWayList>(res); instance.setData(this, 'notifyWays'); this.isNotifyLoading = false; if (this.isCreated) return; this.$nextTick(() => { this.formData.notify_ways = []; }); }); } // 接口拉取数据质量的事件类型 getDataQualityEventTypes() { getDataQualityEventTypes('data_quality').then(res => { if (res.result && res.data) { this.eventTypeList = []; res.data.forEach(item => { this.eventTypeList.push({ id: item.event_type_name, name: item.event_type_alias, }); }); } }); } /** * handleRuleNameChange * @param ruleName */ handleRuleNameChange(ruleName: string) { if (!this.formData.event_alias && ruleName) { this.formData.event_alias = `${ruleName}的事件`; } } /** * clearReceivers */ clearReceivers() { this.receivers = []; } // 获取所有成员名单,获取成员 getProjectMember() { this.isReceiverLoading = true; this.axios.get('projects/list_all_user/').then(res => { if (res.result) { this.userList = res.data.map(user => ({ id: user, name: user })); } else { this.getMethodWarning(res.message, res.code); } this.isReceiverLoading = false; }); } /** * handleInputChange * @param value */ handleInputChange(value: string) { this.selectionStart = this.$refs.textareaInput.$refs.textarea.selectionStart; if (value[this.selectionStart - 1] === '$') { this.$refs.dropdown.isShow = true; this.isDropdownShow = true; } else { this.isDropdownShow = false; } } /** * handleStopOver */ handleStopOver() { this.selectionStart = this.$refs.textareaInput.$refs.textarea.selectionStart; const value = this.formData.event_detail_template[this.selectionStart - 1]; if (value === '$') { this.isDropdownShow = true; } else { this.isDropdownShow = false; } } /** * triggerHandler * @param data */ triggerHandler(data: IAuditEventTempData) { const left = this.formData.event_detail_template.slice(0, this.selectionStart - 1); const right = this.formData.event_detail_template.slice(this.selectionStart); this.formData.event_detail_template = left + '${' + data.varName + '}' + right; this.$refs.dropdown.isShow = false; this.$refs.textareaInput.focus(); this.selectionStart = 0; } /** * handleTempSelect * @param id * @param data */ handleTempSelect(id: number, data: IRuleTemplateData) { this.formData.event_sub_type = data.template_name; if (this.isCreated) { this.$bkInfo({ theme: 'warning', title: '此操作存在风险', subTitle: '更换模板后,原规则配置将会被覆盖,是否继续?', confirmFn: () => { this.formData.rule_config = JSON.parse(JSON.stringify(data.template_config.default_rule_config)); this.modelLimitMetrics = data.template_config.limit_metrics; this.isCoveredConfig = true; }, }); } else { this.isCoveredConfig = true; this.formData.rule_config = JSON.parse(JSON.stringify(data.template_config.default_rule_config)); this.modelLimitMetrics = data.template_config.limit_metrics; } } /** * backFillData * @param data * @param isEdit */ backFillData(data: IRuleConfigFields, isEdit?= true) { this.isCreated = true; this.formData = data; // 告警接收人 this.receivers = this.formData.receivers; // 收敛策略 const { duration, alert_threshold, mask_time } = this.formData.convergence_config; this.alertConfigInfo.trigger_config.duration = duration; this.alertConfigInfo.trigger_config.alert_threshold = alert_threshold; this.alertConfigInfo.convergence_config.mask_time = mask_time; this.isEdit = isEdit; this.getModelLimitMetrics(); } /** * getModelLimitMetrics */ getModelLimitMetrics() { if (this.ruleTemplateList.length && this.formData.rule_template_id) { this.modelLimitMetrics = this.ruleTemplateList.find(item => item.id === this.formData.rule_template_id) .template_config.limit_metrics; } } /** * handleCloseRuleTemplate */ handleCloseRuleTemplate() { this.isShowRuleModel = false; } /** * validatorRuleContent * @returns */ validatorRuleContent() { const self = this; return function (val: []) { return self.ruleContent.length > 0; }; } /** * submitData */ submitData() { this.formData.rule_config_alias = this.ruleContent; this.isChecking = true; this.$refs.validateForm1.validate().then( () => { if (this.isCreated) { this.updateQualityRules(); } else { this.createQualityRules(); } }, () => { this.isChecking = false; } ); } /** * eventFucus */ eventFucus() { this.isShowTableSelect = true; this.eventType = 'number'; } /** * eventLeave */ eventLeave() { this.isShowTableSelect = false; this.eventType = 'textarea'; } // 质量事件查看指标接口 getAuditEventTemp() { getAuditEventTemp().then(res => { const instance = new BKHttpResponse<IAuditEventTemp>(res); instance.setData(this, 'auditEventTempList'); this.$nextTick(() => { this.isShowDropContent = true; }); }); } // 获取规则配置函数列表 public queryQualityRuleFunc() { this.isRuleFuncLoading = true; queryQualityRuleFunc(this.DataId).then(res => { const instance = new BKHttpResponse<IQualityRuleFunc>(res); instance.setData(this, 'ruleFuncList'); this.isRuleFuncLoading = false; }); } // 获取规则配置指标列表 public queryQualityRuleIndex() { this.isRuleIndexLoading = true; queryQualityRuleIndex(this.DataId).then(res => { const instance = new BKHttpResponse<IQualityRuleIndex>(res); instance.setData(this, 'ruleIndexList'); this.isRuleIndexLoading = false; }); } // 获取规则配置模板列表 public queryQualityRuleTemplates() { this.isRuleTemplateLoading = true; queryQualityRuleTemplates(this.DataId).then(res => { const instance = new BKHttpResponse<IQualityRuleTemplate>(res, false); instance.setData(this, 'ruleTemplateList'); this.isRuleTemplateLoading = false; this.getModelLimitMetrics(); }); } /** * 新建规则 */ createQualityRules() { this.formData.data_set_id = this.DataId; createQualityRules(this.formData).then(res => { if (res.data) { showMsg('新建审核规则成功!', 'success', { delay: 2500 }); this.$emit('close'); } this.isChecking = false; }); } /** * 保存规则 */ updateQualityRules() { this.formData.data_set_id = this.DataId; updateQualityRules(this.formData).then(res => { if (res.data) { showMsg('更新审核规则成功!', 'success', { delay: 2500 }); this.$emit('close'); } this.isChecking = false; }); } }
the_stack
import ts from 'typescript'; // import { createFunctionInlineTransformer } from './inlineWrappedFunctions'; import { matchWrappedInvocation, matchWrapping } from './patterns'; import { createProgramFromSource } from './createTSprogram'; import { InlineContext } from './inlineWrappedFunctions'; const deriveNewFuncName = (funcName: string) => funcName + '_unwrapped'; type WrappedUsage = { arity: number; // expected arity of the function being unwrapped inside funcDeclaration: ts.VariableDeclaration; funcName: string; parameterName: string; parameterPos: number; funcExpression: ts.FunctionExpression; callExpression: ts.CallExpression; }; export const createPassUnwrappedFunctionsTransformer = ( getCtx: () => InlineContext | undefined ): ts.TransformerFactory<ts.SourceFile> => (context) => { getCtx; return (sourceFile) => { const foundFunctions = new Map<string, WrappedUsage | 'bail_out'>(); const [program, copiedSource] = createProgramFromSource(sourceFile); const typeChecker = program.getTypeChecker(); const collectFunctions = (node: ts.Node): ts.VisitResult<ts.Node> => { const invocation = matchWrappedInvocation(node); if (invocation) { const { arity, callExpression, calleeName: funcName } = invocation; const symbol = typeChecker.getSymbolAtLocation(funcName); const [declaration] = symbol?.declarations || []; if ( declaration && ts.isParameter(declaration) && ts.isIdentifier(declaration.name) && ts.isFunctionExpression(declaration.parent) && ts.isVariableDeclaration(declaration.parent.parent) && ts.isIdentifier(declaration.parent.parent.name) ) { const funcDeclaration = declaration.parent.parent; const func = declaration.parent; const parameterPos = func.parameters.findIndex( (p) => p === declaration ); const funcName = declaration.parent.parent.name.text; const existing = foundFunctions.get(funcName); if (!existing) { foundFunctions.set(funcName, { arity, callExpression, funcDeclaration: funcDeclaration, funcExpression: func, parameterPos, funcName, parameterName: declaration.name.text, }); } else if (existing !== 'bail_out') { // it means that we already registered this function // we will need to bail out if: // 1. it is a different argument, we don't yet unwrap for two // 2. arity of the call doesn't match if ( existing.parameterPos !== parameterPos || existing.arity !== arity ) { foundFunctions.set(funcName, 'bail_out'); } } } } return ts.visitEachChild(node, collectFunctions, context); }; const addFunctionsWithoutUnwrapping = ( node: ts.Node ): ts.VisitResult<ts.Node> => { if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) { const funcToModify = foundFunctions.get(node.name.text); if (funcToModify && funcToModify !== 'bail_out') { let bailOut = false; const modifyFunction = ( nodeInModfifyFunc: ts.Node ): ts.VisitResult<ts.Node> => { if ( ts.isCallExpression(nodeInModfifyFunc) && ts.isIdentifier(nodeInModfifyFunc.expression) ) { const match = matchWrappedInvocation(nodeInModfifyFunc); if ( match && match.calleeName.text === funcToModify.parameterName && match.arity === funcToModify.arity ) { // transforms A2(func, a,b) into func(a,b) return ts.createCall( match.calleeName, undefined, // recursively transform all calls within a function match.args.map((arg) => ts.visitNode(arg, modifyFunction)) ); } const calledFuncIdentifier = nodeInModfifyFunc.expression; // can be a curried version of callee name in the same body // example: A2(func, a,b) and func(c) if ( calledFuncIdentifier.text === funcToModify.parameterName && nodeInModfifyFunc.arguments.length === 1 && funcToModify.arity !== 1 ) { // means that we have an invocation that is not uniform with expected arity // therefore we cannot pass a raw function to it bailOut = true; } // recursive call to itself if (calledFuncIdentifier.text === funcToModify.funcName) { return ts.createCall( ts.createIdentifier(deriveNewFuncName(funcToModify.funcName)), undefined, nodeInModfifyFunc.arguments.map((arg) => ts.visitNode(arg, modifyFunction) ) ); } // now it can be a call to another function but with passed in parameter // that is now unwrapped // thus check if we have an unwrapped version if ( nodeInModfifyFunc.arguments.some( (arg) => ts.isIdentifier(arg) && arg.text === funcToModify.parameterName ) ) { const existingUnwrappedFunc = foundFunctions.get( calledFuncIdentifier.text ); if ( // todo we need to bail out because we cannot find an unwrapped version !existingUnwrappedFunc || existingUnwrappedFunc === 'bail_out' || // we need to make sure that arity matches // TODO make sure that the position matches too, e.g. it is the same parameter existingUnwrappedFunc.arity !== funcToModify.arity ) { bailOut = true; } return ts.createCall( ts.createIdentifier( deriveNewFuncName(calledFuncIdentifier.text) ), undefined, nodeInModfifyFunc.arguments.map((arg) => ts.visitNode(arg, modifyFunction) ) ); } } return ts.visitEachChild( nodeInModfifyFunc, modifyFunction, context ); }; const newFuncExpression = ts.visitNode( funcToModify.funcExpression, modifyFunction ); if (bailOut) { foundFunctions.delete(funcToModify.funcName); } else { return [ node, ts.createVariableDeclaration( deriveNewFuncName(funcToModify.funcName), undefined, newFuncExpression ), ]; } } } return ts.visitEachChild(node, addFunctionsWithoutUnwrapping, context); }; const replaceUsagesWithUnwrappedVersion = ( node: ts.Node ): ts.VisitResult<ts.Node> => { if (ts.isCallExpression(node)) { const { expression } = node; if (ts.isIdentifier(expression)) { // todo make it a map maybe? const funcToUnwrap = foundFunctions.get(expression.text); if ( funcToUnwrap && funcToUnwrap !== 'bail_out' && // actually the same symbol typeChecker.getSymbolAtLocation(expression) === typeChecker.getSymbolAtLocation(funcToUnwrap.funcDeclaration.name) ) { const args = node.arguments; const argPos = funcToUnwrap.parameterPos; const funcParameter: ts.Expression | undefined = args[argPos]; if (funcParameter) { const match = matchWrapping(funcParameter); // it means that it is something like (..., F3(function (a,b,c) {...}), ...) if (match) { return ts.createCall( ts.createIdentifier(deriveNewFuncName(expression.text)), undefined, [ ...args .slice(0, funcToUnwrap.parameterPos) .map((a) => ts.visitNode(a, replaceUsagesWithUnwrappedVersion) ), ts.visitNode( match.wrappedExpression, replaceUsagesWithUnwrappedVersion ), ...args .slice(argPos + 1) .map((a) => ts.visitNode(a, replaceUsagesWithUnwrappedVersion) ), ] ); } else if (ts.isIdentifier(funcParameter)) { const existingSplit = getCtx()?.splits.get(funcParameter.text); // if (funcParameter.text) if ( existingSplit && existingSplit.arity === funcToUnwrap.arity ) { return ts.createCall( ts.createIdentifier(deriveNewFuncName(expression.text)), undefined, [ ...args .slice(0, funcToUnwrap.parameterPos) .map((a) => ts.visitNode(a, replaceUsagesWithUnwrappedVersion) ), ts.createIdentifier(existingSplit.rawLambdaName), ...args .slice(argPos + 1) .map((a) => ts.visitNode(a, replaceUsagesWithUnwrappedVersion) ), ] ); } } } } } } return ts.visitEachChild( node, replaceUsagesWithUnwrappedVersion, context ); }; ts.visitNode(copiedSource, collectFunctions); const withUnwrappedFunctions = ts.visitNode( copiedSource, addFunctionsWithoutUnwrapping ); const withInlinedCalls = ts.visitNode( withUnwrappedFunctions, replaceUsagesWithUnwrappedVersion ); return withInlinedCalls; }; };
the_stack
import { formatStats } from './formatStats'; import { formatDate } from './formatDate'; export function transformData(data, groupAccessor, ordinalAccessor, valueAccessor) { // transform data to below format // [{label: "2018", "A": 23, "B": 7, "C": 11}, {label: ..}] const dataArr = []; data.forEach(obj => { let o = {}; if (!dataArr.length) { o[groupAccessor] = obj[groupAccessor]; o[obj[ordinalAccessor]] = obj[valueAccessor]; dataArr.push(o); } else { o = dataArr.filter(d => d[groupAccessor] === obj[groupAccessor]).pop(); if (!!o) { const idx = dataArr.findIndex(d => d[groupAccessor] === obj[groupAccessor]); o[obj[ordinalAccessor]] = obj[valueAccessor]; dataArr[idx] = o; } else { o = {}; o[groupAccessor] = obj[groupAccessor]; o[obj[ordinalAccessor]] = obj[valueAccessor]; dataArr.push(o); } } }); return dataArr; } export const accessorFormatMap = { number: '0[.][0][0]a', date: '%B %d %Y', percent: '0[.][0][0]%', string: '' }; export const accessorFormats = { valueAccessor: 'number', nodeSizeAccessor: 'number', latitudeAccessor: 'number', longitudeAccessor: 'number', xAccessor: [ { charts: ['scatter-plot'], type: 'number' } ], yAccessor: [ { charts: ['scatter-plot'], type: 'number' } ] }; export const orderColumns = { 'alluvial-diagram': ['sourceAccessor', 'targetAccessor', 'groupAccessor', 'valueAccessor'], 'bar-chart': ['ordinalAccessor', 'valueAccessor', 'groupAccessor'], 'clustered-bar-chart': ['groupAccessor', 'ordinalAccessor', 'valueAccessor'], 'stacked-bar-chart': ['groupAccessor', 'ordinalAccessor', 'valueAccessor'], 'line-chart': ['seriesAccessor', 'ordinalAccessor', 'valueAccessor'], 'pie-chart': ['ordinalAccessor', 'valueAccessor'], 'scatter-plot': ['groupAccessor', 'xAccessor', 'yAccessor'], 'heat-map': ['xAccessor', 'yAccessor', 'valueAccessor'], 'circle-packing': ['clusterAccessor', 'nodeAccessor', 'nodeSizeAccessor', 'idAccessor'], 'parallel-plot': ['seriesAccessor', 'ordinalAccessor', 'valueAccessor'], 'dumbbell-plot': ['seriesAccessor', 'ordinalAccessor', 'valueAccessor'], 'world-map': ['markerNameAccessor', 'joinNameAccessor', 'valueAccessor'] }; export const chartAccessors = { singleAccessors: [ 'valueAccessor', 'sizeAccessor', 'xAccessor', 'yAccessor', 'latitudeAccessor', 'longitudeAccessor', 'ordinalAccessor', 'idAccessor', 'markerAccessor', 'markerNameAccessor', 'joinAccessor', 'joinNameAccessor', 'nodeAccessor', 'parentAccessor', 'groupAccessor', 'seriesAccessor', 'filterAccessor', 'sourceAccessor', 'targetAccessor' ], arrayAccessors: ['interactionKeys'], nestedAccessors: [ { objectName: 'tooltipLabel', objectAccessors: ['labelAccessor'], formatAccessors: ['format'] }, { objectName: 'accessibility', objectAccessors: ['elementDescriptionAccessor'] }, { objectName: 'dataLabel', objectAccessors: ['labelAccessor'], formatAccessors: ['format'] } ] }; export function orderScopedData(_this, dataSample, chartType) { const tableColumns = []; orderColumns[chartType].forEach(col => { if (_this[col]) { tableColumns.push(_this[col]); } }); Object.keys(dataSample).forEach(key => { if (tableColumns.indexOf(key) < 0) { tableColumns.push(key); } }); return tableColumns; } export function getScopedData(data, keyMap) { const scopedData = []; data.forEach(dataRecord => { const scopedDataRecord = {}; // loop through target fields instead of all data record fields Object.keys(keyMap).forEach(field => { // check if we have a date object, if we do format with provided or default date format if (dataRecord[field] instanceof Date) { scopedDataRecord[field] = formatDate({ date: dataRecord[field], format: keyMap[field] ? keyMap[field] : accessorFormatMap['date'], offsetTimezone: true }); } else { if (keyMap[field] === 'normalized') { scopedDataRecord[field] = keyMap[field] && dataRecord[field] ? formatStats(dataRecord[field], accessorFormatMap['number']) : dataRecord[field]; scopedDataRecord[`${field}%`] = keyMap[field] && dataRecord[field] && dataRecord.getSum ? formatStats(dataRecord[field] / dataRecord.getSum(), accessorFormatMap['percent']) : dataRecord[field]; } else { scopedDataRecord[field] = keyMap[field] && dataRecord[field] ? formatStats(dataRecord[field], keyMap[field]) : dataRecord[field]; } } }); scopedData.push(scopedDataRecord); }); return scopedData; } export function getDefaultFormat(accessor, formats, formatMap, chartType) { // we are going to use a map for now instead of finding the type of the data in the data row if (formats[accessor]) { if (formats[accessor] instanceof Array) { // we have chart specific stuff let mappedFormat = undefined; formats[accessor].forEach(formatObj => { if (formatObj.charts.indexOf(chartType) >= 0) { mappedFormat = formatMap[formatObj.type]; } else { mappedFormat = mappedFormat ? mappedFormat : (mappedFormat = ''); } }); return mappedFormat; } else { // we can simple return default type based on value if (formatMap[formats[accessor]]) { return formatMap[formats[accessor]]; } else { return ''; } } } else { return ''; } } export function scopeDataKeys(_this, accessors, chartType, skipSorting?) { // this doesn't work need to get the list of props on the element. let valueKeyMap = {}; let valueKeyHash = {}; // first we do nested accessors, starting with tooltip if (accessors.nestedAccessors && accessors.nestedAccessors instanceof Array) { accessors.nestedAccessors.forEach(accessor => { if (accessor.objectName && accessor.objectAccessors && accessor.objectAccessors instanceof Array) { if (_this[accessor.objectName]) { accessor.objectAccessors.forEach((k, i) => { if (_this[accessor.objectName][k] instanceof Array) { _this[accessor.objectName][k].forEach((innerK, j) => { // is there an associated format that is an array? if (!valueKeyHash[innerK]) { valueKeyMap[innerK] = accessor.formatAccessors && accessor.formatAccessors instanceof Array && _this[accessor.objectName][accessor.formatAccessors[i]] ? _this[accessor.objectName][accessor.formatAccessors[i]][j] : undefined; valueKeyHash[innerK] = 1; } }); } else { if (_this[accessor.objectName][k] && !valueKeyHash[_this[accessor.objectName][k]]) { valueKeyMap[_this[accessor.objectName][k]] = accessor.formatAccessors ? _this[accessor.objectName][accessor.formatAccessors] : undefined; valueKeyHash[_this[accessor.objectName][k]] = 1; } } }); } } }); } // next we do singleAccessors, make sure it exists and is an array if (accessors.singleAccessors && accessors.singleAccessors instanceof Array) { accessors.singleAccessors.forEach(accessor => { // now we check whether the chart has the accessor for each if (_this[accessor] && !valueKeyHash[_this[accessor]]) { const defFormat = getDefaultFormat(accessor, accessorFormats, accessorFormatMap, chartType); valueKeyMap[_this[accessor]] = defFormat; valueKeyHash[_this[accessor]] = 1; } }); } // next we do array accessors if (accessors.arrayAccessors && accessors.arrayAccessors instanceof Array) { accessors.arrayAccessors.forEach(accessor => { if (_this[accessor]) { _this[accessor].forEach(k => { if (!valueKeyHash[k] && k !== 'xAccessor' && k !== 'yAccessor') { // have to account for mutation of heat-map interaction key props valueKeyMap[k] = undefined; valueKeyHash[k] = 1; } }); } }); } if (!skipSorting) { const newKeyMap = {}; const correctKeysInOrder = orderScopedData(_this, valueKeyMap, chartType); correctKeysInOrder.forEach(key => { newKeyMap[key] = valueKeyMap[key]; }); valueKeyMap = newKeyMap; } return valueKeyMap; } // this operation happens in-place (it mutates the incoming data, must duplicate before sending when necessary) export function fixNestedSparseness( data: any, ordinalAccessor: string, groupAccessor: string, valueAccessor: string, defaultValue?: number ) { // full group is what an ideal group will look like in the nest const fullGroup = {}; // currentNest is what the current nest looks like, we check its sparseness against fullGroup const currentNest = {}; // we will now populate fullGroup and currentNest data.forEach(datum => { // make sure the ideal group has every ordinal value we encounter fullGroup[datum[ordinalAccessor]] = 1; // check if we have a group in the nest yet if (!currentNest[datum[groupAccessor]]) { // initialize the group if we don't currentNest[datum[groupAccessor]] = {}; } // add the ordinal value to the current group currentNest[datum[groupAccessor]][datum[ordinalAccessor]] = 1; }); // we create this array once, so we don't have to repeat it inside our looping const everyOrdinal = Object.keys(fullGroup); // now that we know what the nest looks like, we are checking sparseness against fullGroup Object.keys(currentNest).forEach(groupValue => { // everyOrdinal has the "perfect" group (non-sparse), so we use it to compare everyOrdinal.forEach(ordinalValue => { // we check each group's ordinals against everyOrdinal, one at a time if (!currentNest[groupValue][ordinalValue]) { // when we encounter a missing item in the current nest, we add to the original array const missingPiece = {}; // make sure we always have some kind of numeric value here if one is not sent missingPiece[valueAccessor] = defaultValue || 0; missingPiece[ordinalAccessor] = ordinalValue; missingPiece[groupAccessor] = groupValue; // now our data contains each missing piece it requires data.push(missingPiece); } }); }); }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/workspaceConnectionsMappers"; import * as Parameters from "../models/parameters"; import { AzureMachineLearningWorkspacesContext } from "../azureMachineLearningWorkspacesContext"; /** Class representing a WorkspaceConnections. */ export class WorkspaceConnections { private readonly client: AzureMachineLearningWorkspacesContext; /** * Create a WorkspaceConnections. * @param {AzureMachineLearningWorkspacesContext} client Reference to the service client. */ constructor(client: AzureMachineLearningWorkspacesContext) { this.client = client; } /** * List all connections under a AML workspace. * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param [options] The optional parameters * @returns Promise<Models.WorkspaceConnectionsListResponse> */ list(resourceGroupName: string, workspaceName: string, options?: Models.WorkspaceConnectionsListOptionalParams): Promise<Models.WorkspaceConnectionsListResponse>; /** * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param callback The callback */ list(resourceGroupName: string, workspaceName: string, callback: msRest.ServiceCallback<Models.PaginatedWorkspaceConnectionsList>): void; /** * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param options The optional parameters * @param callback The callback */ list(resourceGroupName: string, workspaceName: string, options: Models.WorkspaceConnectionsListOptionalParams, callback: msRest.ServiceCallback<Models.PaginatedWorkspaceConnectionsList>): void; list(resourceGroupName: string, workspaceName: string, options?: Models.WorkspaceConnectionsListOptionalParams | msRest.ServiceCallback<Models.PaginatedWorkspaceConnectionsList>, callback?: msRest.ServiceCallback<Models.PaginatedWorkspaceConnectionsList>): Promise<Models.WorkspaceConnectionsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, options }, listOperationSpec, callback) as Promise<Models.WorkspaceConnectionsListResponse>; } /** * Add a new workspace connection. * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param connectionName Friendly name of the workspace connection * @param parameters The object for creating or updating a new workspace connection * @param [options] The optional parameters * @returns Promise<Models.WorkspaceConnectionsCreateResponse> */ create(resourceGroupName: string, workspaceName: string, connectionName: string, parameters: Models.WorkspaceConnectionDto, options?: msRest.RequestOptionsBase): Promise<Models.WorkspaceConnectionsCreateResponse>; /** * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param connectionName Friendly name of the workspace connection * @param parameters The object for creating or updating a new workspace connection * @param callback The callback */ create(resourceGroupName: string, workspaceName: string, connectionName: string, parameters: Models.WorkspaceConnectionDto, callback: msRest.ServiceCallback<Models.WorkspaceConnection>): void; /** * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param connectionName Friendly name of the workspace connection * @param parameters The object for creating or updating a new workspace connection * @param options The optional parameters * @param callback The callback */ create(resourceGroupName: string, workspaceName: string, connectionName: string, parameters: Models.WorkspaceConnectionDto, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WorkspaceConnection>): void; create(resourceGroupName: string, workspaceName: string, connectionName: string, parameters: Models.WorkspaceConnectionDto, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WorkspaceConnection>, callback?: msRest.ServiceCallback<Models.WorkspaceConnection>): Promise<Models.WorkspaceConnectionsCreateResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, connectionName, parameters, options }, createOperationSpec, callback) as Promise<Models.WorkspaceConnectionsCreateResponse>; } /** * Get the detail of a workspace connection. * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param connectionName Friendly name of the workspace connection * @param [options] The optional parameters * @returns Promise<Models.WorkspaceConnectionsGetResponse> */ get(resourceGroupName: string, workspaceName: string, connectionName: string, options?: msRest.RequestOptionsBase): Promise<Models.WorkspaceConnectionsGetResponse>; /** * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param connectionName Friendly name of the workspace connection * @param callback The callback */ get(resourceGroupName: string, workspaceName: string, connectionName: string, callback: msRest.ServiceCallback<Models.WorkspaceConnection>): void; /** * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param connectionName Friendly name of the workspace connection * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, workspaceName: string, connectionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WorkspaceConnection>): void; get(resourceGroupName: string, workspaceName: string, connectionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WorkspaceConnection>, callback?: msRest.ServiceCallback<Models.WorkspaceConnection>): Promise<Models.WorkspaceConnectionsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, connectionName, options }, getOperationSpec, callback) as Promise<Models.WorkspaceConnectionsGetResponse>; } /** * Delete a workspace connection. * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param connectionName Friendly name of the workspace connection * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, workspaceName: string, connectionName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param connectionName Friendly name of the workspace connection * @param callback The callback */ deleteMethod(resourceGroupName: string, workspaceName: string, connectionName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName Name of the resource group in which workspace is located. * @param workspaceName Name of Azure Machine Learning workspace. * @param connectionName Friendly name of the workspace connection * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, workspaceName: string, connectionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, workspaceName: string, connectionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, connectionName, options }, deleteMethodOperationSpec, callback); } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/connections", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.workspaceName ], queryParameters: [ Parameters.apiVersion, Parameters.target, Parameters.category ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PaginatedWorkspaceConnectionsList }, default: { bodyMapper: Mappers.MachineLearningServiceError } }, serializer }; const createOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/connections/{connectionName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.workspaceName, Parameters.connectionName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.WorkspaceConnectionDto, required: true } }, responses: { 200: { bodyMapper: Mappers.WorkspaceConnection }, default: { bodyMapper: Mappers.MachineLearningServiceError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/connections/{connectionName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.workspaceName, Parameters.connectionName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.WorkspaceConnection }, default: { bodyMapper: Mappers.MachineLearningServiceError } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/connections/{connectionName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.workspaceName, Parameters.connectionName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.MachineLearningServiceError } }, serializer };
the_stack
import { IsoPoint } from "../../../engine/lib/IsoPoint" import { Matrix } from "../../../engine/lib/util/Matrix" import { PRIORITY } from "../room.constants" import { RoomEngine } from "../Room.engine" import { Wall } from "./Wall" const WALL_HEIGHT = 92 const WALL_SIZE = 32 const WALL_THICKNESS = 8 export type PointLike = { x: number, y: number } export class WallRenderer { constructor (private roomEngine: RoomEngine) {} public walls: Matrix<Wall | null> public door: PointLike public spawn: PointLike private maxHeight: number get heightmap () { return this.roomEngine.heightmap } renderWalls() { this.walls = new Matrix(this.heightmap.width, this.heightmap.height) this.setupDoor() this.maxHeight = this.heightmap.reduce((max, z) => Math.max(max, z * 32), -Infinity) this.renderHorizontalWalls() this.renderVerticalWalls() } private setupDoor () { this.door = this.getExistentDoor() || this.lookForArbitraryDoor() if (!this.spawn) this.spawn = this.door } private getExistentDoor () { if (!this.spawn) { return } const spawnBlock = this.heightmap.get(this.spawn.x, this.spawn.y) // Descartar a localização do spawn se não houver bloco no local if (!spawnBlock) { this.spawn = null return } // Verifica se é um local válido para a renderização de uma porta let spawnIsDoor: boolean = false // Vertical wall spawnIsDoor = spawnIsDoor || this.heightmap .neighborsOf(this.spawn.x, this.spawn.y, [ Matrix.NEIGHBORS.TOP, Matrix.NEIGHBORS.LEFT, Matrix.NEIGHBORS.BOTTOM, ]) .every(b => !b) // Horizontal Wall spawnIsDoor = spawnIsDoor || this.heightmap .neighborsOf(this.spawn.x, this.spawn.y, [ Matrix.NEIGHBORS.LEFT, Matrix.NEIGHBORS.TOP, Matrix.NEIGHBORS.RIGHT, ]) .every(b => !b) if (spawnIsDoor) { return this.spawn } } private lookForArbitraryDoor () { const maxDoorX = this.heightmap.width let door: PointLike // Procurando porta apenas na parede vertical for (let y = 0; y < this.heightmap.height; y++) { for (let x = 0; x <= maxDoorX; x++) { const z = this.heightmap.get(x, y) // Don't test with falsy valued blocks if (!z) continue if (this.isValidDoorBlock(x, y)) { door = { x, y } return door } break } } return door } private isValidDoorBlock (x: number, y: number) { return this.heightmap .neighborsOf(x, y, [Matrix.NEIGHBORS.TOP, Matrix.NEIGHBORS.BOTTOM, Matrix.NEIGHBORS.LEFT]) .every(b => !b) } private renderHorizontalWalls () { let maxWallY = this.heightmap.height // Paredes Horizontais for (let x = 0; x < this.heightmap.width; x++) { // Percorre as colunas até o primeiro bloco vertical for (let y = 0; y <= maxWallY; y++) { if (x === this.door?.x && y === this.door?.y) continue const z = this.heightmap.get(x, y) // Se for 0, não inserir paredes if (!z) continue let wallLength = 1 // Se o bloco atual deve renderizar uma porta const isDoor = x === this.door?.x && y - 1 === this.door?.y // Se o bloco atual não for uma porta, calcula o tamanho da parede if (!isDoor) { wallLength = this.calcHorizontalConnectedWallsLength(x, y) } // Não enfileirar paredes horizontais verticalmente maxWallY = y const elevation = (z - 1) * 32 // Encontra os vizinhos de cima e de baixo sucessivamente para encontrar // o menor Z ligado ao bloco atual let minNeighborZ = z Array.from([Matrix.NEIGHBORS.LEFT, Matrix.NEIGHBORS.RIGHT]) .map(r => { const nx = r.x + x const ny = r.y + y return { x: nx, y: ny, z: this.heightmap.get(nx, ny), next: r, } }) .forEach(neigh => { while (neigh?.z) { minNeighborZ = Math.min(neigh.z, minNeighborZ) // Se houver um bloco para tras para a verificação const backBlock = { x: neigh.x, y: neigh.y - 1 } if ( this.heightmap.get(backBlock.x, backBlock.y) && !(backBlock.x == this.door?.x && backBlock.y == this.door?.y) ) break const nextNeighX = neigh.x + neigh.next.x const nextNeighY = neigh.y + neigh.next.y neigh = { ...neigh, x: nextNeighX, y: nextNeighY, z: this.heightmap.get(nextNeighX, nextNeighY), } } }) // Calcula a menor elevação ligada ao bloco atual const minZElevation = (minNeighborZ - 1) * WALL_SIZE const height = this.maxHeight + WALL_HEIGHT - minZElevation const width = WALL_SIZE * wallLength // Elevação relativa a elevação do bloco com o menor z const relativeElevation = elevation - minZElevation // Renderiza const texture = this.roomEngine.roomImager.generateWallTexture( 1, width, height, isDoor, WALL_THICKNESS, isDoor, relativeElevation, ) // Calcula a posição de renderização da parede const posX = (x + 1) * WALL_SIZE const posY = y * WALL_SIZE const posZ = height + 20 + minZElevation // + (wallLength - 1) * (WALL_SIZE / 2) const position = new IsoPoint(posX, posY, posZ) const wall = new Wall(texture, position) wall.zIndex = this.roomEngine.calcZIndex( { x, y, z, }, PRIORITY.WALL_H, ) this.walls.set(x, y, wall) this.roomEngine.container.addChild(wall) // Pula para o x apos a ultima parede inserida x += wallLength - 1 } } } private calcHorizontalConnectedWallsLength (x: number, y: number) { let wallLength = 1 for (let neighborX = x + 1; neighborX < this.heightmap.width; neighborX++) { const neighborZ = this.heightmap.get(neighborX, y) const isBlockEmpty = !neighborZ if (isBlockEmpty) break // Stops verifying for connected walls if there's a block behind const blockBehind = this.heightmap.get(neighborX, y - 1) if (blockBehind) break wallLength++ } return wallLength } private renderVerticalWalls () { // X máximo onde pode haver paredes let maxWallX = this.heightmap.width // Paredes Verticais for (let y = 0; y < this.heightmap.height; y++) { for (let x = 0; x <= maxWallX; x++) { // Se for o bloco da porta ignora if (x === this.door?.x && y === this.door?.y) continue // Não testa blocos com 0 const z = this.heightmap.get(x, y) if (!z) continue // Verifica so o bloco atual deve renderizar uma porta const isDoor = x - 1 === this.door?.x && y === this.door?.y // Comprimento da parede let wallLength = 1 // Se o bloco atual não for uma porta, calcula o tamanho da parede if (!isDoor) { let neighY = y + 1 let neighX = x do { // Para a verificação de paredes conexas ao encontrar um bloco nulo let neighZ = this.heightmap.get(neighX, neighY) if (!neighZ) break // Para a verificação de paredes conexas ao encontrar uma possível parede atras const backBlock = { x: neighX - 1, y: neighY } if (this.heightmap.get(backBlock.x, backBlock.y)) break wallLength++ neighY++ } while (neighY < this.heightmap.height) } const elevation = (z - 1) * WALL_SIZE // Define a posição X máxima para o bloco atual maxWallX = x // Encontra os vizinhos de cima e de baixo sucessivamente para encontrar // o menor Z ligado ao bloco atual let minNeighborZ = z Array.from([Matrix.NEIGHBORS.TOP, Matrix.NEIGHBORS.BOTTOM]) .map(r => { const nx = r.x + x const ny = r.y + y return { x: nx, y: ny, z: this.heightmap.get(nx, ny), next: r, } }) .forEach(neigh => { while (neigh?.z) { minNeighborZ = Math.min(neigh.z, minNeighborZ) // Se houver um bloco para tras para a verificação const backBlock = { x: neigh.x - 1, y: neigh.y } if ( this.heightmap.get(backBlock.x, backBlock.y) && !(backBlock.x == this.door?.x && backBlock.y == this.door?.y) ) break const nextNeighX = neigh.x + neigh.next.x const nextNeighY = neigh.y + neigh.next.y neigh = { ...neigh, x: nextNeighX, y: nextNeighY, z: this.heightmap.get(nextNeighX, nextNeighY), } } }) // Calcula a menor elevação ligada ao bloco atual const minZElevation = (minNeighborZ - 1) * WALL_SIZE const height = this.maxHeight + WALL_HEIGHT - minZElevation const width = wallLength * WALL_SIZE const isConner = !!this.walls.get(x, y) // Elevação relativa a elevação do bloco com o menor z const relativeElevation = elevation - minZElevation // Renderiza const texture = this.roomEngine.roomImager.generateWallTexture( 0, width, height, isDoor, WALL_THICKNESS, isConner, relativeElevation, ) // Calcula a posição de renderização da parede const posX = x * WALL_SIZE - WALL_THICKNESS const posY = (y + wallLength - 1) * WALL_SIZE const posZ = height + minZElevation + (wallLength - 1) * (WALL_SIZE / 2) const position = new IsoPoint(posX, posY, posZ) const wall = new Wall(texture, position) if (isConner) position .add(0, 0, 4) .toPoint() .copyTo(wall.position) wall.zIndex = this.roomEngine.calcZIndex( { x, y, z, }, PRIORITY.WALL_V, ) this.walls.set(x, y, wall) this.roomEngine.container.addChild(wall) // Pula para o y depois da parede gerada y += wallLength - 1 } } } }
the_stack
import { CfnResource, IConstruct } from '@aws-cdk/core'; import { NagPack, NagMessageLevel, NagPackProps } from '../nag-pack'; import { APIGWAccessLogging, APIGWAssociatedWithWAF, APIGWAuthorization, APIGWExecutionLoggingEnabled, APIGWRequestValidation, } from '../rules/apigw'; import { AppSyncGraphQLRequestLogging } from '../rules/appsync'; import { AthenaWorkgroupEncryptedQueryResults } from '../rules/athena'; import { AutoScalingGroupCooldownPeriod, AutoScalingGroupHealthCheck, AutoScalingGroupScalingNotifications, } from '../rules/autoscaling'; import { Cloud9InstanceNoIngressSystemsManager } from '../rules/cloud9'; import { CloudFrontDistributionAccessLogging, CloudFrontDistributionGeoRestrictions, CloudFrontDistributionNoOutdatedSSL, CloudFrontDistributionS3OriginAccessIdentity, CloudFrontDistributionWAFIntegration, } from '../rules/cloudfront'; import { CodeBuildProjectKMSEncryptedArtifacts, CodeBuildProjectManagedImages, CodeBuildProjectPrivilegedModeDisabled, } from '../rules/codebuild'; import { CognitoUserPoolAdvancedSecurityModeEnforced, CognitoUserPoolAPIGWAuthorizer, CognitoUserPoolMFA, CognitoUserPoolNoUnauthenticatedLogins, CognitoUserPoolStrongPasswordPolicy, } from '../rules/cognito'; import { DocumentDBClusterBackupRetentionPeriod, DocumentDBClusterEncryptionAtRest, DocumentDBClusterLogExports, DocumentDBClusterNonDefaultPort, DocumentDBCredentialsInSecretsManager, } from '../rules/documentdb'; import { DAXEncrypted, DynamoDBPITREnabled } from '../rules/dynamodb'; import { EC2EBSVolumeEncrypted, EC2InstanceDetailedMonitoringEnabled, EC2InstanceTerminationProtection, EC2RestrictedInbound, EC2SecurityGroupDescription, } from '../rules/ec2'; import { ECROpenAccess } from '../rules/ecr'; import { ECSClusterCloudWatchContainerInsights, ECSTaskDefinitionContainerLogging, } from '../rules/ecs'; import { EFSEncrypted } from '../rules/efs'; import { ElastiCacheClusterInVPC, ElastiCacheClusterNonDefaultPort, ElastiCacheRedisClusterEncryption, ElastiCacheRedisClusterMultiAZ, ElastiCacheRedisClusterRedisAuth, } from '../rules/elasticache'; import { ElasticBeanstalkEC2InstanceLogsToS3, ElasticBeanstalkManagedUpdatesEnabled, ElasticBeanstalkVPCSpecified, } from '../rules/elasticbeanstalk'; import { CLBConnectionDraining, CLBNoInboundHttpHttps, ELBCrossZoneLoadBalancingEnabled, ELBLoggingEnabled, ELBTlsHttpsListenersOnly, } from '../rules/elb'; import { EMRAuthEC2KeyPairOrKerberos, EMRS3AccessLogging } from '../rules/emr'; import { IAMNoManagedPolicies, IAMNoWildcardPermissions } from '../rules/iam'; import { KinesisDataAnalyticsFlinkCheckpointing, KinesisDataFirehoseSSE, KinesisDataStreamDefaultKeyWhenSSE, KinesisDataStreamSSE, } from '../rules/kinesis'; import { KMSBackingKeyRotationEnabled } from '../rules/kms'; import { MediaStoreCloudWatchMetricPolicy, MediaStoreContainerAccessLogging, MediaStoreContainerCORSPolicy, MediaStoreContainerHasContainerPolicy, MediaStoreContainerLifecyclePolicy, } from '../rules/mediastore'; import { MSKBrokerLogging, MSKBrokerToBrokerTLS, MSKClientToBrokerTLS, } from '../rules/msk'; import { NeptuneClusterAutomaticMinorVersionUpgrade, NeptuneClusterBackupRetentionPeriod, NeptuneClusterEncryptionAtRest, NeptuneClusterIAMAuth, NeptuneClusterMultiAZ, } from '../rules/neptune'; import { OpenSearchAllowlistedIPs, OpenSearchDedicatedMasterNode, OpenSearchEncryptedAtRest, OpenSearchInVPCOnly, OpenSearchNodeToNodeEncryption, OpenSearchNoUnsignedOrAnonymousAccess, OpenSearchSlowLogsToCloudWatch, OpenSearchZoneAwareness, } from '../rules/opensearch'; import { QuicksightSSLConnections } from '../rules/quicksight'; import { AuroraMySQLBacktrack, AuroraMySQLLogging, AuroraMySQLPostgresIAMAuth, RDSInstanceBackupEnabled, RDSInstanceDeletionProtectionEnabled, RDSNonDefaultPort, RDSStorageEncrypted, } from '../rules/rds'; import { RedshiftClusterAuditLogging, RedshiftBackupEnabled, RedshiftClusterEncryptionAtRest, RedshiftClusterInVPC, RedshiftClusterNonDefaultPort, RedshiftClusterNonDefaultUsername, RedshiftClusterPublicAccess, RedshiftClusterUserActivityLogging, RedshiftClusterVersionUpgrade, RedshiftRequireTlsSSL, } from '../rules/redshift'; import { S3BucketLevelPublicAccessProhibited, S3BucketLoggingEnabled, S3BucketServerSideEncryptionEnabled, S3BucketSSLRequestsOnly, } from '../rules/s3'; import { SageMakerNotebookInstanceKMSKeyConfigured, SageMakerNotebookInVPC, SageMakerNotebookNoDirectInternetAccess, } from '../rules/sagemaker'; import { SecretsManagerRotationEnabled } from '../rules/secretsmanager'; import { SNSEncryptedKMS } from '../rules/sns'; import { SQSQueueDLQ, SQSQueueSSE } from '../rules/sqs'; import { StepFunctionStateMachineAllLogsToCloudWatch, StepFunctionStateMachineXray, } from '../rules/stepfunctions'; import { TimestreamDatabaseCustomerManagedKey } from '../rules/timestream'; import { VPCFlowLogsEnabled, VPCNoNACLs } from '../rules/vpc'; /** * Check Best practices based on AWS Solutions Security Matrix * */ export class AwsSolutionsChecks extends NagPack { constructor(props?: NagPackProps) { super(props); this.packName = 'AwsSolutions'; } public visit(node: IConstruct): void { if (node instanceof CfnResource) { this.checkCompute(node); this.checkStorage(node); this.checkDatabases(node); this.checkNetworkDelivery(node); this.checkManagementGovernance(node); this.checkMachineLearning(node); this.checkAnalytics(node); this.checkSecurityCompliance(node); this.checkServerless(node); this.checkApplicationIntegration(node); this.checkMediaServices(node); this.checkDeveloperTools(node); } } /** * Check Compute Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkCompute(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'EB1', info: 'The Elastic Beanstalk environment is not configured to use a specific VPC.', explanation: 'Use a non-default in order to seperate your environment from default resources.', level: NagMessageLevel.ERROR, rule: ElasticBeanstalkVPCSpecified, node: node, }); this.applyRule({ ruleSuffixOverride: 'EB3', info: 'The Elastic Beanstalk environment does not have managed updates enabled.', explanation: 'Enable managed platform updates for beanstalk environments in order to receive bug fixes, software updates and new features. Managed platform updates perform immutable environment updates.', level: NagMessageLevel.ERROR, rule: ElasticBeanstalkManagedUpdatesEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'EB4', info: 'The Elastic Beanstalk environment does not upload EC2 Instance logs to S3.', explanation: 'Beanstalk environment logs should be retained and uploaded to Amazon S3 in order to keep the logging data for future audits, historical purposes or to track and analyze the EB application environment behavior for a long period of time.', level: NagMessageLevel.WARN, rule: ElasticBeanstalkEC2InstanceLogsToS3, node: node, }); this.applyRule({ ruleSuffixOverride: 'EC23', info: 'The Security Group allows for 0.0.0.0/0 or ::/0 inbound access.', explanation: 'Large port ranges, when open, expose instances to unwanted attacks. More than that, they make traceability of vulnerabilities very difficult. For instance, your web servers may only require 80 and 443 ports to be open, but not all. One of the most common mistakes observed is when all ports for 0.0.0.0/0 range are open in a rush to access the instance. EC2 instances must expose only to those ports enabled on the corresponding security group level.', level: NagMessageLevel.ERROR, rule: EC2RestrictedInbound, node: node, }); this.applyRule({ ruleSuffixOverride: 'EC26', info: 'The EBS volume has encryption disabled.', explanation: "With EBS encryption, you aren't required to build, maintain, and secure your own key management infrastructure. EBS encryption uses KMS keys when creating encrypted volumes and snapshots. This helps protect data at rest.", level: NagMessageLevel.ERROR, rule: EC2EBSVolumeEncrypted, node: node, }); this.applyRule({ ruleSuffixOverride: 'EC27', info: 'The Security Group does not have a description.', explanation: 'Descriptions help simplify operations and remove any opportunities for operator errors.', level: NagMessageLevel.ERROR, rule: EC2SecurityGroupDescription, node: node, }); this.applyRule({ ruleSuffixOverride: 'EC28', info: 'The EC2 instance/AutoScaling launch configuration does not have detailed monitoring enabled.', explanation: 'Monitoring data helps make better decisions on architecting and managing compute resources.', level: NagMessageLevel.ERROR, rule: EC2InstanceDetailedMonitoringEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'EC29', info: 'The EC2 instance is not part of an ASG and has Termination Protection disabled.', explanation: 'Termination Protection safety feature enabled in order to protect the instances from being accidentally terminated.', level: NagMessageLevel.ERROR, rule: EC2InstanceTerminationProtection, node: node, }); this.applyRule({ ruleSuffixOverride: 'ECR1', info: 'The ECR Repository allows open access.', explanation: 'Removing * principals in an ECR Repository helps protect against unauthorized access.', level: NagMessageLevel.ERROR, rule: ECROpenAccess, node: node, }); this.applyRule({ ruleSuffixOverride: 'ECS4', info: 'The ECS Cluster has CloudWatch Container Insights disabled.', explanation: 'CloudWatch Container Insights allow operators to gain a better perspective on how the cluster’s applications and microservices are performing.', level: NagMessageLevel.ERROR, rule: ECSClusterCloudWatchContainerInsights, node: node, }); this.applyRule({ ruleSuffixOverride: 'ECS7', info: 'The ECS Task Definition does not have awslogs logging enabled at the minimum.', explanation: 'Container logging allows operators to view and aggregate the logs from the container.', level: NagMessageLevel.ERROR, rule: ECSTaskDefinitionContainerLogging, node: node, }); this.applyRule({ ruleSuffixOverride: 'ELB1', info: 'The CLB is used for incoming HTTP/HTTPS traffic. Use ALBs instead.', explanation: 'HTTP/HTTPS applications (monolithic or containerized) should use the ALB instead of the CLB for enhanced incoming traffic distribution, better performance and lower costs.', level: NagMessageLevel.ERROR, rule: CLBNoInboundHttpHttps, node: node, }); this.applyRule({ ruleSuffixOverride: 'ELB2', info: 'The ELB does not have access logs enabled.', explanation: 'Access logs allow operators to to analyze traffic patterns and identify and troubleshoot security issues.', level: NagMessageLevel.ERROR, rule: ELBLoggingEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'ELB3', info: 'The CLB does not have connection draining enabled.', explanation: 'With Connection Draining feature enabled, if an EC2 backend instance fails health checks The CLB will not send any new requests to the unhealthy instance. However, it will still allow existing (in-flight) requests to complete for the duration of the configured timeout.', level: NagMessageLevel.ERROR, rule: CLBConnectionDraining, node: node, }); this.applyRule({ ruleSuffixOverride: 'ELB4', info: 'The CLB does not use at least two AZs with the Cross-Zone Load Balancing feature enabled.', explanation: 'CLBs can distribute the traffic evenly across all backend instances. To use Cross-Zone Load Balancing at optimal level, the system should maintain an equal EC2 capacity distribution in each of the AZs registered with the load balancer.', level: NagMessageLevel.ERROR, rule: ELBCrossZoneLoadBalancingEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'ELB5', info: 'The CLB listener is not configured for secure (HTTPs or SSL) protocols for client communication.', explanation: 'The HTTPs or SSL protocols enable secure communication by encrypting the communication between the client and the load balancer.', level: NagMessageLevel.ERROR, rule: ELBTlsHttpsListenersOnly, node: node, }); } /** * Check Storage Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkStorage(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'S1', info: 'The S3 Bucket has server access logs disabled.', explanation: 'The bucket should have server access logging enabled to provide detailed records for the requests that are made to the bucket.', level: NagMessageLevel.ERROR, rule: S3BucketLoggingEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'S2', info: 'The S3 Bucket does not have public access restricted and blocked.', explanation: 'The bucket should have public access restricted and blocked to prevent unauthorized access.', level: NagMessageLevel.ERROR, rule: S3BucketLevelPublicAccessProhibited, node: node, }); this.applyRule({ ruleSuffixOverride: 'S3', info: 'The S3 Bucket does not default encryption enabled.', explanation: 'The bucket should minimally have SSE enabled to help protect data-at-rest.', level: NagMessageLevel.ERROR, rule: S3BucketServerSideEncryptionEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'S10', info: 'The S3 Bucket does not require requests to use SSL.', explanation: 'You can use HTTPS (TLS) to help prevent potential attackers from eavesdropping on or manipulating network traffic using person-in-the-middle or similar attacks. You should allow only encrypted connections over HTTPS (TLS) using the aws:SecureTransport condition on Amazon S3 bucket policies.', level: NagMessageLevel.ERROR, rule: S3BucketSSLRequestsOnly, node: node, }); this.applyRule({ ruleSuffixOverride: 'EFS1', info: 'The EFS is not configured for encryption at rest.', explanation: 'By using an encrypted file system, data and metadata are automatically encrypted before being written to the file system. Similarly, as data and metadata are read, they are automatically decrypted before being presented to the application. These processes are handled transparently by EFS without requiring modification of applications.', level: NagMessageLevel.ERROR, rule: EFSEncrypted, node: node, }); } /** * Check Database Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkDatabases(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'RDS2', info: 'The RDS instance or Aurora DB cluster does not have storage encryption enabled.', explanation: 'Storage encryption helps protect data-at-rest by encrypting the underlying storage, automated backups, read replicas, and snapshots for the database.', level: NagMessageLevel.ERROR, rule: RDSStorageEncrypted, node: node, }); this.applyRule({ ruleSuffixOverride: 'RDS6', info: 'The RDS Aurora MySQL/PostgresSQL cluster does not have IAM Database Authentication enabled.', explanation: "With IAM Database Authentication enabled, the system doesn't have to use a password when connecting to the MySQL/PostgreSQL database instances, instead it uses an authentication token.", level: NagMessageLevel.ERROR, rule: AuroraMySQLPostgresIAMAuth, node: node, }); this.applyRule({ ruleSuffixOverride: 'RDS10', info: 'The RDS instance or Aurora DB cluster does not have deletion protection enabled.', explanation: 'The deletion protection feature helps protect the database from being accidentally deleted.', level: NagMessageLevel.ERROR, rule: RDSInstanceDeletionProtectionEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'RDS11', info: 'The RDS instance or Aurora DB cluster uses the default endpoint port.', explanation: 'Port obfuscation (using a non default endpoint port) adds an additional layer of defense against non-targeted attacks (i.e. MySQL/Aurora port 3306, SQL Server port 1433, PostgreSQL port 5432, etc).', level: NagMessageLevel.ERROR, rule: RDSNonDefaultPort, node: node, }); this.applyRule({ ruleSuffixOverride: 'RDS13', info: 'The RDS instance is not configured for automated backups.', explanation: 'Automated backups allow for point-in-time recovery.', level: NagMessageLevel.ERROR, rule: RDSInstanceBackupEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'RDS14', info: 'The RDS Aurora MySQL cluster does not have Backtrack enabled.', explanation: 'Backtrack helps order to rewind cluster tables to a specific time, without using backups.', level: NagMessageLevel.ERROR, rule: AuroraMySQLBacktrack, node: node, }); this.applyRule({ ruleSuffixOverride: 'RDS15', info: 'The RDS DB instance or Aurora DB cluster does not have deletion protection enabled.', explanation: 'Enabling Deletion Protection at the cluster level for Amazon Aurora databases or instance level for non Aurora instances helps protect from accidental deletion.', level: NagMessageLevel.ERROR, rule: RDSInstanceDeletionProtectionEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'RDS16', info: 'The RDS Aurora MySQL serverless cluster does not have audit, error, general, and slowquery Log Exports enabled.', explanation: 'This allows operators to use CloudWatch to view logs to help diagnose problems in the database.', level: NagMessageLevel.ERROR, rule: AuroraMySQLLogging, node: node, }); this.applyRule({ ruleSuffixOverride: 'DDB3', info: 'The DynamoDB table does not have Point-in-time Recovery enabled.', explanation: 'DynamoDB continuous backups represent an additional layer of insurance against accidental loss of data on top of on-demand backups. The DynamoDB service can back up the data with per-second granularity and restore it to any single second from the time PITR was enabled up to the prior 35 days.', level: NagMessageLevel.WARN, rule: DynamoDBPITREnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'DDB4', info: 'The DAX cluster does not have server-side encryption enabled.', explanation: 'Data in cache, configuration data and log files should be encrypted using Server-Side Encryption in order to protect from unauthorized access to the underlying storage.', level: NagMessageLevel.ERROR, rule: DAXEncrypted, node: node, }); this.applyRule({ ruleSuffixOverride: 'AEC1', info: 'The ElastiCache cluster is not provisioned in a VPC.', explanation: 'Provisioning the cluster within a VPC allows for better flexibility and control over the cache clusters security, availability, traffic routing and more.', level: NagMessageLevel.ERROR, rule: ElastiCacheClusterInVPC, node: node, }); this.applyRule({ ruleSuffixOverride: 'AEC3', info: 'The ElastiCache Redis cluster does not have both encryption in transit and at rest enabled.', explanation: 'Encryption in transit helps secure communications to the cluster. Encryption at rest helps protect data at rest from unauthorized access.', level: NagMessageLevel.ERROR, rule: ElastiCacheRedisClusterEncryption, node: node, }); this.applyRule({ ruleSuffixOverride: 'AEC4', info: 'The ElastiCache Redis cluster is not deployed in a Multi-AZ configuration.', explanation: 'The cluster should use a Multi-AZ deployment configuration for high availability.', level: NagMessageLevel.ERROR, rule: ElastiCacheRedisClusterMultiAZ, node: node, }); this.applyRule({ ruleSuffixOverride: 'AEC5', info: 'The ElastiCache cluster uses the default endpoint port.', explanation: 'Port obfuscation (using a non default endpoint port) adds an additional layer of defense against non-targeted attacks (i.e. Redis port 6379 and Memcached port 11211).', level: NagMessageLevel.ERROR, rule: ElastiCacheClusterNonDefaultPort, node: node, }); this.applyRule({ ruleSuffixOverride: 'AEC6', info: 'The ElastiCache Redis cluster does not use Redis AUTH for user authentication.', explanation: 'Redis authentication tokens enable Redis to require a token (password) before allowing clients to execute commands, thereby improving data security.', level: NagMessageLevel.ERROR, rule: ElastiCacheRedisClusterRedisAuth, node: node, }); this.applyRule({ ruleSuffixOverride: 'N1', info: 'The Neptune DB cluster is not deployed in a Multi-AZ configuration.', explanation: 'The cluster should use a Multi-AZ deployment configuration for high availability.', level: NagMessageLevel.ERROR, rule: NeptuneClusterMultiAZ, node: node, }); this.applyRule({ ruleSuffixOverride: 'N2', info: 'The Neptune DB instance does have Auto Minor Version Upgrade enabled.', explanation: 'The Neptune service regularly releases engine updates. Enabling Auto Minor Version Upgrade will allow the service to automatically apply these upgrades to DB Instances.', level: NagMessageLevel.ERROR, rule: NeptuneClusterAutomaticMinorVersionUpgrade, node: node, }); this.applyRule({ ruleSuffixOverride: 'N3', info: 'The Neptune DB cluster does not have a reasonable minimum backup retention period configured.', explanation: 'The retention period represents the number of days to retain automated snapshots. A minimum retention period of 7 days is recommended but can be adjust to meet system requirements.', level: NagMessageLevel.ERROR, rule: NeptuneClusterBackupRetentionPeriod, node: node, }); this.applyRule({ ruleSuffixOverride: 'N4', info: 'The Neptune DB cluster does not have encryption at rest enabled.', explanation: 'Encrypting data-at-rest protects data confidentiality and prevents unauthorized users from accessing sensitive information.', level: NagMessageLevel.ERROR, rule: NeptuneClusterEncryptionAtRest, node: node, }); this.applyRule({ ruleSuffixOverride: 'N5', info: 'The Neptune DB cluster does not have IAM Database Authentication enabled.', explanation: "With IAM Database Authentication enabled, the system doesn't have to use a password when connecting to the cluster.", level: NagMessageLevel.ERROR, rule: NeptuneClusterIAMAuth, node: node, }); this.applyRule({ ruleSuffixOverride: 'RS1', info: 'The Redshift cluster does not require TLS/SSL encryption.', explanation: 'Enabling the "require_ssl" parameter secures data-in-transit by encrypting the connection between the clients and the Redshift clusters.', level: NagMessageLevel.ERROR, rule: RedshiftRequireTlsSSL, node: node, }); this.applyRule({ ruleSuffixOverride: 'RS2', info: 'The Redshift cluster is not provisioned in a VPC.', explanation: 'Provisioning the cluster within a VPC allows for better flexibility and control over the Redshift clusters security, availability, traffic routing and more.', level: NagMessageLevel.ERROR, rule: RedshiftClusterInVPC, node: node, }); this.applyRule({ ruleSuffixOverride: 'RS3', info: 'The Redshift cluster uses the default "awsuser" username.', explanation: 'Using a custom master user name instead of the default master user name (i.e. "awsuser") provides an additional layer of defense against non-targeted attacks.', level: NagMessageLevel.ERROR, rule: RedshiftClusterNonDefaultUsername, node: node, }); this.applyRule({ ruleSuffixOverride: 'RS4', info: 'The Redshift cluster uses the default endpoint port.', explanation: 'Port obfuscation (using a non default endpoint port) adds an additional layer of defense against non-targeted attacks (i.e. Redshift port 5439).', level: NagMessageLevel.ERROR, rule: RedshiftClusterNonDefaultPort, node: node, }); this.applyRule({ ruleSuffixOverride: 'RS5', info: 'The Redshift cluster does not have audit logging enabled.', explanation: 'Audit logging helps operators troubleshoot issues and ensure security.', level: NagMessageLevel.ERROR, rule: RedshiftClusterAuditLogging, node: node, }); this.applyRule({ ruleSuffixOverride: 'RS6', info: 'The Redshift cluster does not have encryption at rest enabled.', explanation: 'Encrypting data-at-rest protects data confidentiality.', level: NagMessageLevel.ERROR, rule: RedshiftClusterEncryptionAtRest, node: node, }); this.applyRule({ ruleSuffixOverride: 'RS8', info: 'The Redshift cluster is publicly accessible.', explanation: 'Disabling public accessibility helps minimize security risks.', level: NagMessageLevel.ERROR, rule: RedshiftClusterPublicAccess, node: node, }); this.applyRule({ ruleSuffixOverride: 'RS9', info: 'The Redshift cluster does not have version upgrade enabled.', explanation: 'Version Upgrade must enabled to enable the cluster to automatically receive upgrades during the maintenance window.', level: NagMessageLevel.ERROR, rule: RedshiftClusterVersionUpgrade, node: node, }); this.applyRule({ ruleSuffixOverride: 'RS10', info: 'The Redshift cluster does not have a retention period for automated snapshots configured.', explanation: 'The retention period represents the number of days to retain automated snapshots. A positive retention period should be set to configure this feature.', level: NagMessageLevel.ERROR, rule: RedshiftBackupEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'RS11', info: 'The Redshift cluster does not have user activity logging enabled.', explanation: 'User activity logging logs each query before it is performed on the clusters databse. To enable this feature associate a Resdhsift Cluster Parameter Group with the "enable_user_activity_logging" parameter set to "true".', level: NagMessageLevel.ERROR, rule: RedshiftClusterUserActivityLogging, node: node, }); this.applyRule({ ruleSuffixOverride: 'DOC1', info: 'The Document DB cluster does not have encryption at rest enabled.', explanation: 'Encrypting data-at-rest protects data confidentiality and prevents unauthorized users from accessing sensitive information.', level: NagMessageLevel.ERROR, rule: DocumentDBClusterEncryptionAtRest, node: node, }); this.applyRule({ ruleSuffixOverride: 'DOC2', info: 'The Document DB cluster uses the default endpoint port.', explanation: 'Port obfuscation (using a non default endpoint port) adds an additional layer of defense against non-targeted attacks (i.e. MongoDB port 27017).', level: NagMessageLevel.ERROR, rule: DocumentDBClusterNonDefaultPort, node: node, }); this.applyRule({ ruleSuffixOverride: 'DOC3', info: 'The Document DB cluster does not have the username and password stored in Secrets Manager.', explanation: "Secrets Manager enables operators to replace hardcoded credentials in your code, including passwords, with an API call to Secrets Manager to retrieve the secret programmatically. This helps ensure the secret can't be compromised by someone examining system code, because the secret no longer exists in the code. Also, operators can configure Secrets Manager to automatically rotate the secret for you according to a specified schedule. This enables you to replace long-term secrets with short-term ones, significantly reducing the risk of compromise.", level: NagMessageLevel.ERROR, rule: DocumentDBCredentialsInSecretsManager, node: node, }); this.applyRule({ ruleSuffixOverride: 'DOC4', info: 'The Document DB cluster does not have a reasonable minimum backup retention period configured.', explanation: 'The retention period represents the number of days to retain automated snapshots. A minimum retention period of 7 days is recommended but can be adjust to meet system requirements.', level: NagMessageLevel.ERROR, rule: DocumentDBClusterBackupRetentionPeriod, node: node, }); this.applyRule({ ruleSuffixOverride: 'DOC5', info: 'The Document DB cluster does not have authenticate, createIndex, and dropCollection Log Exports enabled.', explanation: 'This allows operators to use CloudWatch to view logs to help diagnose problems in the database. The events recorded by the AWS DocumentDB audit logs include successful and failed authentication attempts, creating indexes or dropping a collection in a database within the DocumentDB cluster.', level: NagMessageLevel.ERROR, rule: DocumentDBClusterLogExports, node: node, }); this.applyRule({ ruleSuffixOverride: 'TS3', info: 'The Timestream database does not use a Customer Managed KMS Key for at rest encryption.', explanation: 'All Timestream tables in a database are encrypted at rest by default using AWS Managed Key. These keys are rotated every three years. Data at rest must be encrypted using CMKs if you require more control over the permissions and lifecycle of your keys, including the ability to have them automatically rotated on an annual basis.', level: NagMessageLevel.WARN, rule: TimestreamDatabaseCustomerManagedKey, node: node, }); } /** * Check Network and Delivery Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkNetworkDelivery(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'VPC3', info: 'A Network ACL or Network ACL entry has been implemented.', explanation: 'Network ACLs should be used sparingly for the following reasons: they can be complex to manage, they are stateless, every IP address must be explicitly opened in each (inbound/outbound) direction, and they affect a complete subnet. Use security groups when possible as they are stateful and easier to manage.', level: NagMessageLevel.WARN, rule: VPCNoNACLs, node: node, }); this.applyRule({ ruleSuffixOverride: 'VPC7', info: 'The VPC does not have an associated Flow Log.', explanation: 'VPC Flow Logs capture network flow information for a VPC, subnet, or network interface and stores it in Amazon CloudWatch Logs. Flow log data can help customers troubleshoot network issues; for example, to diagnose why specific traffic is not reaching an instance, which might be a result of overly restrictive security group rules.', level: NagMessageLevel.ERROR, rule: VPCFlowLogsEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'CFR1', info: 'The CloudFront distribution may require Geo restrictions.', explanation: 'Geo restriction may need to be enabled for the distribution in order to allow or deny a country in order to allow or restrict users in specific locations from accessing content.', level: NagMessageLevel.WARN, rule: CloudFrontDistributionGeoRestrictions, node: node, }); this.applyRule({ ruleSuffixOverride: 'CFR2', info: 'The CloudFront distribution may require integration with AWS WAF.', explanation: 'The Web Application Firewall can help protect against application-layer attacks that can compromise the security of the system or place unnecessary load on them.', level: NagMessageLevel.WARN, rule: CloudFrontDistributionWAFIntegration, node: node, }); this.applyRule({ ruleSuffixOverride: 'CFR3', info: 'The CloudFront distributions does not have access logging enabled.', explanation: 'Enabling access logs helps operators track all viewer requests for the content delivered through the Content Delivery Network.', level: NagMessageLevel.ERROR, rule: CloudFrontDistributionAccessLogging, node: node, }); this.applyRule({ ruleSuffixOverride: 'CFR5', info: 'The CloudFront distributions uses SSLv3 or TLSv1 for communication to the origin.', explanation: 'Vulnerabilities have been and continue to be discovered in the deprecated SSL and TLS protocols. Using a security policy with minimum TLSv1.1 or TLSv1.2 and appropriate security ciphers for HTTPS helps protect viewer connections.', level: NagMessageLevel.ERROR, rule: CloudFrontDistributionNoOutdatedSSL, node: node, }); this.applyRule({ ruleSuffixOverride: 'CFR6', info: 'The CloudFront distribution does not use an origin access identity an S3 origin.', explanation: 'Origin access identities help with security by restricting any direct access to objects through S3 URLs.', level: NagMessageLevel.ERROR, rule: CloudFrontDistributionS3OriginAccessIdentity, node: node, }); this.applyRule({ ruleSuffixOverride: 'APIG1', info: 'The API does not have access logging enabled.', explanation: 'Enabling access logs helps operators view who accessed an API and how the caller accessed the API.', level: NagMessageLevel.ERROR, rule: APIGWAccessLogging, node: node, }); this.applyRule({ ruleSuffixOverride: 'APIG2', info: 'The REST API does not have request validation enabled.', explanation: 'The API should have basic request validation enabled. If the API is integrated with custom source (Lambda, ECS, etc..) in the backend, deeper input validation should be considered for implementation.', level: NagMessageLevel.ERROR, rule: APIGWRequestValidation, node: node, }); this.applyRule({ ruleSuffixOverride: 'APIG3', info: 'The REST API stage is not associated with AWS WAFv2 web ACL.', explanation: 'AWS WAFv2 is a web application firewall that helps protect web applications and APIs from attacks by allowing configured rules to allow, block, or monitor (count) web requests based on customizable rules and conditions that are defined.', level: NagMessageLevel.WARN, rule: APIGWAssociatedWithWAF, node: node, }); this.applyRule({ ruleSuffixOverride: 'APIG4', info: 'The API does not implement authorization.', explanation: 'In most cases an API needs to have an authentication and authorization implementation strategy. This includes using such approaches as IAM, Cognito User Pools, Custom authorizer, etc.', level: NagMessageLevel.ERROR, rule: APIGWAuthorization, node: node, }); this.applyRule({ ruleSuffixOverride: 'APIG6', info: 'The REST API Stage does not have CloudWatch logging enabled for all methods.', explanation: 'Enabling CloudWatch logs at the stage level helps operators to track and analyze execution behavior at the API stage level.', level: NagMessageLevel.ERROR, rule: APIGWExecutionLoggingEnabled, node: node, }); } /** * Check Management and Governance Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkManagementGovernance(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'AS1', info: 'The Auto Scaling Group does not have a cooldown period.', explanation: 'A cooldown period temporarily suspends any scaling activities in order to allow the newly launched EC2 instance(s) some time to start handling the application traffic.', level: NagMessageLevel.ERROR, rule: AutoScalingGroupCooldownPeriod, node: node, }); this.applyRule({ ruleSuffixOverride: 'AS2', info: 'The Auto Scaling Group does not have properly configured health checks.', explanation: 'The health check feature enables the service to detect whether its registered EC2 instances are healthy or not.', level: NagMessageLevel.ERROR, rule: AutoScalingGroupHealthCheck, node: node, }); this.applyRule({ ruleSuffixOverride: 'AS3', info: 'The Auto Scaling Group does not have notifications configured for all scaling events.', explanation: 'Notifications on EC2 instance launch, launch error, termination, and termination errors allow operators to gain better insights into systems attributes such as activity and health.', level: NagMessageLevel.ERROR, rule: AutoScalingGroupScalingNotifications, node: node, }); } /** * Check Machine Learning Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkMachineLearning(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'SM1', info: 'The SageMaker notebook instance is not provisioned inside a VPC.', explanation: 'Provisioning the notebook instances inside a VPC enables the notebook to access VPC-only resources such as EFS file systems.', level: NagMessageLevel.ERROR, rule: SageMakerNotebookInVPC, node: node, }); this.applyRule({ ruleSuffixOverride: 'SM2', info: 'The SageMaker notebook instance does not have an encrypted storage volume.', explanation: 'Encrypting storage volumes helps protect SageMaker data-at-rest.', level: NagMessageLevel.ERROR, rule: SageMakerNotebookInstanceKMSKeyConfigured, node: node, }); this.applyRule({ ruleSuffixOverride: 'SM3', info: 'The SageMaker notebook instance has direct internet access enabled.', explanation: 'Disabling public accessibility helps minimize security risks.', level: NagMessageLevel.ERROR, rule: SageMakerNotebookNoDirectInternetAccess, node: node, }); } /** * Check Analytics Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkAnalytics(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'ATH1', info: 'The Athena workgroup does not encrypt query results.', explanation: 'Encrypting query results stored in S3 helps secure data to meet compliance requirements for data-at-rest encryption.', level: NagMessageLevel.ERROR, rule: AthenaWorkgroupEncryptedQueryResults, node: node, }); this.applyRule({ ruleSuffixOverride: 'EMR2', info: 'The EMR cluster does not have S3 logging enabled.', explanation: 'Uploading logs to S3 enables the system to keep the logging data for historical purposes or to track and analyze the clusters behavior.', level: NagMessageLevel.ERROR, rule: EMRS3AccessLogging, node: node, }); this.applyRule({ ruleSuffixOverride: 'EMR6', info: 'The EMR cluster does not implement authentication via an EC2 Key Pair or Kerberos.', explanation: 'SSH clients can use an EC2 key pair to authenticate to cluster instances. Alternatively, with EMR release version 5.10.0 or later, solutions can configure Kerberos to authenticate users and SSH connections to the master node.', level: NagMessageLevel.ERROR, rule: EMRAuthEC2KeyPairOrKerberos, node: node, }); this.applyRule({ ruleSuffixOverride: 'KDA3', info: 'The Kinesis Data Analytics Flink Application does not have checkpointing enabled.', explanation: 'Checkpoints are backups of application state that KDA automatically creates periodically and uses to restore from faults.', level: NagMessageLevel.WARN, rule: KinesisDataAnalyticsFlinkCheckpointing, node: node, }); this.applyRule({ ruleSuffixOverride: 'KDF1', info: 'The Kinesis Data Firehose delivery stream does have server-side encryption enabled.', explanation: 'This allows the system to meet strict regulatory requirements and enhance the security of system data.', level: NagMessageLevel.ERROR, rule: KinesisDataFirehoseSSE, node: node, }); this.applyRule({ ruleSuffixOverride: 'KDS1', info: 'The Kinesis Data Stream does not has server-side encryption enabled.', explanation: "Data is encrypted before it's written to the Kinesis stream storage layer, and decrypted after it’s retrieved from storage. This allows the system to meet strict regulatory requirements and enhance the security of system data.", level: NagMessageLevel.ERROR, rule: KinesisDataStreamSSE, node: node, }); this.applyRule({ ruleSuffixOverride: 'KDS3', info: 'The Kinesis Data Stream specifies server-side encryption and does not use the "aws/kinesis" key.', explanation: 'Customer Managed Keys can incur additional costs that scale with the amount of consumers and producers. Ensure that Customer Managed Keys are required for compliance before using them (https://docs.aws.amazon.com/streams/latest/dev/costs-performance.html).', level: NagMessageLevel.WARN, rule: KinesisDataStreamDefaultKeyWhenSSE, node: node, }); this.applyRule({ ruleSuffixOverride: 'MSK2', info: 'The MSK cluster uses plaintext communication between clients and brokers.', explanation: 'TLS only communication secures data-in-transit by encrypting the connection between the clients and brokers.', level: NagMessageLevel.ERROR, rule: MSKClientToBrokerTLS, node: node, }); this.applyRule({ ruleSuffixOverride: 'MSK3', info: 'The MSK cluster uses plaintext communication between brokers.', explanation: 'TLS communication secures data-in-transit by encrypting the connection between brokers.', level: NagMessageLevel.ERROR, rule: MSKBrokerToBrokerTLS, node: node, }); this.applyRule({ ruleSuffixOverride: 'MSK6', info: 'The MSK cluster does not send broker logs to a supported destination.', explanation: 'Broker logs enable operators to troubleshoot Apache Kafka applications and to analyze their communications with the MSK cluster. The cluster can deliver logs to the following resources: a CloudWatch log group, an S3 bucket, a Kinesis Data Firehose delivery stream.', level: NagMessageLevel.ERROR, rule: MSKBrokerLogging, node: node, }); this.applyRule({ ruleSuffixOverride: 'OS1', info: 'The OpenSearch Service domain is not provisioned inside a VPC.', explanation: 'Provisioning the domain within a VPC enables better flexibility and control over the clusters access and security as this feature keeps all traffic between the VPC and OpenSearch domains within the AWS network instead of going over the public Internet.', level: NagMessageLevel.ERROR, rule: OpenSearchInVPCOnly, node: node, }); this.applyRule({ ruleSuffixOverride: 'OS2', info: 'The OpenSearch Service domain does not have node-to-node encryption enabled.', explanation: 'Enabling the node-to-node encryption feature adds an extra layer of data protection on top of the existing ES security features such as HTTPS client to cluster encryption and data-at-rest encryption.', level: NagMessageLevel.ERROR, rule: OpenSearchNodeToNodeEncryption, node: node, }); this.applyRule({ ruleSuffixOverride: 'OS3', info: 'The OpenSearch Service domain does not only grant access via allowlisted IP addresses.', explanation: 'Using allowlisted IP addresses helps protect the domain against unauthorized access.', level: NagMessageLevel.ERROR, rule: OpenSearchAllowlistedIPs, node: node, }); this.applyRule({ ruleSuffixOverride: 'OS4', info: 'The OpenSearch Service domain does not use dedicated master nodes.', explanation: 'Using dedicated master nodes helps improve environmental stability by offloading all the management tasks from the data nodes.', level: NagMessageLevel.ERROR, rule: OpenSearchDedicatedMasterNode, node: node, }); this.applyRule({ ruleSuffixOverride: 'OS5', info: 'The OpenSearch Service domain does not allow for unsigned requests or anonymous access.', explanation: 'Restricting public access helps prevent unauthorized access and prevents any unsigned requests to be made to the resources.', level: NagMessageLevel.ERROR, rule: OpenSearchNoUnsignedOrAnonymousAccess, node: node, }); this.applyRule({ ruleSuffixOverride: 'OS7', info: 'The OpenSearch Service domain does not have Zone Awareness enabled.', explanation: 'Enabling cross-zone replication (Zone Awareness) increases the availability of the OpenSearch Service domain by allocating the nodes and replicate the data across two AZs in the same region in order to prevent data loss and minimize downtime in the event of node or AZ failure.', level: NagMessageLevel.ERROR, rule: OpenSearchZoneAwareness, node: node, }); this.applyRule({ ruleSuffixOverride: 'OS8', info: 'The OpenSearch Service domain does not have encryption at rest enabled.', explanation: 'Encrypting data-at-rest protects data confidentiality and prevents unauthorized users from accessing sensitive information.', level: NagMessageLevel.ERROR, rule: OpenSearchEncryptedAtRest, node: node, }); this.applyRule({ ruleSuffixOverride: 'OS9', info: 'The OpenSearch Service domain does not minimally publish SEARCH_SLOW_LOGS and INDEX_SLOW_LOGS to CloudWatch Logs.', explanation: 'These logs enable operators to gain full insight into the performance of these operations.', level: NagMessageLevel.ERROR, rule: OpenSearchSlowLogsToCloudWatch, node: node, }); this.applyRule({ ruleSuffixOverride: 'QS1', info: 'The Quicksight data sources connection is not configured to use SSL.', explanation: 'SSL secures communications to data sources, especially when using public networks. Using SSL with QuickSight requires the use of certificates signed by a publicly-recognized certificate authority.', level: NagMessageLevel.ERROR, rule: QuicksightSSLConnections, node: node, }); } /** * Check Security and Compliance Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkSecurityCompliance(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'IAM4', info: 'The IAM user, role, or group uses AWS managed policies.', explanation: 'An AWS managed policy is a standalone policy that is created and administered by AWS. Currently, many AWS managed policies do not restrict resource scope. Replace AWS managed policies with system specific (customer) managed policies.', level: NagMessageLevel.ERROR, rule: IAMNoManagedPolicies, node: node, }); this.applyRule({ ruleSuffixOverride: 'IAM5', info: 'The IAM entity contains wildcard permissions and does not have a cdk_nag rule suppression with evidence for those permission.', explanation: 'Metadata explaining the evidence (e.g. via supporting links) for wildcard permissions allows for transparency to operators.', level: NagMessageLevel.ERROR, rule: IAMNoWildcardPermissions, node: node, }); this.applyRule({ ruleSuffixOverride: 'COG1', info: 'The Cognito user pool does not have a password policy that minimally specify a password length of at least 8 characters, as well as requiring uppercase, numeric, and special characters.', explanation: 'Strong password policies increase system security by encouraging users to create reliable and secure passwords.', level: NagMessageLevel.ERROR, rule: CognitoUserPoolStrongPasswordPolicy, node: node, }); this.applyRule({ ruleSuffixOverride: 'COG2', info: 'The Cognito user pool does not require MFA.', explanation: 'Multi-factor authentication (MFA) increases security for the application by adding another authentication method, and not relying solely on user name and password.', level: NagMessageLevel.WARN, rule: CognitoUserPoolMFA, node: node, }); this.applyRule({ ruleSuffixOverride: 'COG3', info: 'The Cognito user pool does not have AdvancedSecurityMode set to ENFORCED.', explanation: 'Advanced security features enable the system to detect and act upon malicious sign-in attempts.', level: NagMessageLevel.ERROR, rule: CognitoUserPoolAdvancedSecurityModeEnforced, node: node, }); this.applyRule({ ruleSuffixOverride: 'COG4', info: 'The API GW method does not use a Cognito user pool authorizer.', explanation: 'API Gateway validates the tokens from a successful user pool authentication, and uses them to grant your users access to resources including Lambda functions, or your own API.', level: NagMessageLevel.ERROR, rule: CognitoUserPoolAPIGWAuthorizer, node: node, }); this.applyRule({ ruleSuffixOverride: 'COG7', info: 'The Cognito identity pool allows for unauthenticated logins and does not have a cdk_nag rule suppression with a reason.', explanation: 'In many cases applications do not warrant unauthenticated guest access applications. Metadata explaining the use case allows for transparency to operators.', level: NagMessageLevel.ERROR, rule: CognitoUserPoolNoUnauthenticatedLogins, node: node, }); this.applyRule({ ruleSuffixOverride: 'KMS5', info: 'The KMS Symmetric key does not have automatic key rotation enabled.', explanation: 'KMS key rotation allow a system to set an yearly rotation schedule for a KMS key so when a AWS KMS key is required to encrypt new data, the KMS service can automatically use the latest version of the HSA backing key to perform the encryption.', level: NagMessageLevel.ERROR, rule: KMSBackingKeyRotationEnabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'SMG4', info: 'The secret does not have automatic rotation scheduled.', explanation: 'AWS Secrets Manager can be configured to automatically rotate the secret for a secured service or database.', level: NagMessageLevel.ERROR, rule: SecretsManagerRotationEnabled, node: node, }); } /** * Check Serverless Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkServerless(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'ASC3', info: 'The GraphQL API does not have request leveling logging enabled.', explanation: 'It is important to use CloudWatch Logs to log metrics such as who has accessed the GraphQL API, how the caller accessed the API, and invalid requests.', level: NagMessageLevel.ERROR, rule: AppSyncGraphQLRequestLogging, node: node, }); this.applyRule({ ruleSuffixOverride: 'SF1', info: 'The Step Function does not log "ALL" events to CloudWatch Logs.', explanation: 'Logging "ALL" events to CloudWatch logs help operators troubleshoot and audit systems.', level: NagMessageLevel.ERROR, rule: StepFunctionStateMachineAllLogsToCloudWatch, node: node, }); this.applyRule({ ruleSuffixOverride: 'SF2', info: 'The Step Function does not have X-Ray tracing enabled.', explanation: 'X-ray provides an end-to-end view of how an application is performing. This helps operators to discover performance issues, detect permission problems, and track requests made to and from other AWS services.', level: NagMessageLevel.ERROR, rule: StepFunctionStateMachineXray, node: node, }); } /** * Check Application Integration Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkApplicationIntegration(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'SNS2', info: 'The SNS Topic does not have server-side encryption enabled.', explanation: 'Server side encryption adds additional protection of sensitive data delivered as messages to subscribers.', level: NagMessageLevel.ERROR, rule: SNSEncryptedKMS, node: node, }); this.applyRule({ ruleSuffixOverride: 'SQS2', info: 'The SQS Queue does not have server-side encryption enabled.', explanation: 'Server side encryption adds additional protection of sensitive data delivered as messages to subscribers.', level: NagMessageLevel.ERROR, rule: SQSQueueSSE, node: node, }); this.applyRule({ ruleSuffixOverride: 'SQS3', info: 'The SQS queue does not have a dead-letter queue (DLQ) enabled or have a cdk_nag rule suppression indicating it is a DLQ.', explanation: 'Using a DLQ helps maintain the queue flow and avoid losing data by detecting and mitigating failures and service disruptions on time.', level: NagMessageLevel.ERROR, rule: SQSQueueDLQ, node: node, }); } /** * Check Media Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkMediaServices(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'MS1', info: 'The MediaStore container does not have container access logging enabled.', explanation: 'The container should have access logging enabled to provide detailed records for the requests that are made to the container.', level: NagMessageLevel.ERROR, rule: MediaStoreContainerAccessLogging, node: node, }); this.applyRule({ ruleSuffixOverride: 'MS4', info: 'The MediaStore container does not define a metric policy to send metrics to CloudWatch.', explanation: 'Using a combination of MediaStore metrics and CloudWatch alarms helps operators gain better insights into container operations.', level: NagMessageLevel.WARN, rule: MediaStoreCloudWatchMetricPolicy, node: node, }); this.applyRule({ ruleSuffixOverride: 'MS7', info: 'The MediaStore container does not define a container policy.', explanation: 'Using a container policy helps follow the standard security advice of granting least privilege, or granting only the permissions required to allow needed access to the container.', level: NagMessageLevel.WARN, rule: MediaStoreContainerHasContainerPolicy, node: node, }); this.applyRule({ ruleSuffixOverride: 'MS8', info: 'The MediaStore container does not define a CORS policy.', explanation: 'Using a CORS policy helps follow the standard security advice of granting least privilege, or granting only the permissions required to allow needed access to the container.', level: NagMessageLevel.WARN, rule: MediaStoreContainerCORSPolicy, node: node, }); this.applyRule({ ruleSuffixOverride: 'MS10', info: 'The MediaStore container does not define a lifecycle policy.', explanation: 'Many use cases warrant the usage of lifecycle configurations to manage container objects during their lifetime.', level: NagMessageLevel.WARN, rule: MediaStoreContainerLifecyclePolicy, node: node, }); } /** * Check Developer Tools Services * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkDeveloperTools(node: CfnResource): void { this.applyRule({ ruleSuffixOverride: 'CB3', info: 'The CodeBuild project has privileged mode enabled.', explanation: 'Privileged grants elevated rights to the system, which introduces additional risk. Privileged mode should only be set to true only if the build project is used to build Docker images. Otherwise, a build that attempts to interact with the Docker daemon fails.', level: NagMessageLevel.WARN, rule: CodeBuildProjectPrivilegedModeDisabled, node: node, }); this.applyRule({ ruleSuffixOverride: 'CB4', info: 'The CodeBuild project does not use an AWS KMS key for encryption.', explanation: 'Using an AWS KMS key helps follow the standard security advice of granting least privilege to objects generated by the project.', level: NagMessageLevel.ERROR, rule: CodeBuildProjectKMSEncryptedArtifacts, node: node, }); this.applyRule({ ruleSuffixOverride: 'CB5', info: 'The Codebuild project does not use images provided by the CodeBuild service or have a cdk_nag suppression rule explaining the need for a custom image.', explanation: 'Explaining differences/edits to Docker images helps operators better understand system dependencies.', level: NagMessageLevel.WARN, rule: CodeBuildProjectManagedImages, node: node, }); this.applyRule({ ruleSuffixOverride: 'C91', info: 'The Cloud9 instance does not use a no-ingress EC2 instance with AWS Systems Manager.', explanation: 'SSM adds an additional layer of protection as it allows operators to control access through IAM permissions and does not require opening inbound ports.', level: NagMessageLevel.ERROR, rule: Cloud9InstanceNoIngressSystemsManager, node: node, }); } }
the_stack
import * as path from 'path'; import * as fs from 'fs'; import glob from 'glob'; import chalk from 'chalk'; import * as shell from 'shelljs'; import { patchTSModule } from './patcher'; import { getModuleAbsolutePath, getTSModule, getTSPackage, mkdirIfNotExist, TSModule, TSPackage } from './file-utils'; import { appRoot, BackupError, defineProperties, Log, parseOptions, PatchError, PersistenceError, resetOptions, RestoreError, TSPOptions, tspPackageJSON } from './system'; import resolve from 'resolve'; /* ******************************************************************************************************************** * Config * ********************************************************************************************************************/ // region Config shell.config.silent = true; export const SRC_FILES = [ 'tsc.js', 'tsserverlibrary.js', 'typescript.js', 'typescriptServices.js', 'tsserver.js' ]; export const BACKUP_DIRNAME = 'lib-backup'; export const RESOURCES_PATH = path.join(appRoot, tspPackageJSON.directories.resources); export const HOOKS_FILES = [ 'postinstall', 'postinstall.cmd' ]; export const defaultInstallLibraries = [ 'tsc.js', 'typescript.js' ]; // endregion /* ******************************************************************************************************************** * Helpers * ********************************************************************************************************************/ // region Helpers /** * Parse file, array of files, or glob of files and get TSModule info for each */ export function parseFiles(fileOrFilesOrGlob: string | string[], dir: string, includeSrc: boolean = false) { const files = Array.isArray(fileOrFilesOrGlob) ? fileOrFilesOrGlob : fs.existsSync(getModuleAbsolutePath(fileOrFilesOrGlob, dir)) ? [ fileOrFilesOrGlob ] : glob.sync(fileOrFilesOrGlob); const ret = files.map(f => getTSModule(getModuleAbsolutePath(f, dir), includeSrc)); return defineProperties(ret, { patched: { get: () => ret.filter(f => f.patchVersion) }, unPatchable: { get: () => ret.filter(f => !f.canPatch) }, canUpdateOrPatch: { get: () => ret.filter(f => f.canPatch && f.outOfDate) }, patchable: { get: () => ret.filter(f => f.canPatch) }, }); } /** * Create backup of TS Module file */ function backup(tsModule: TSModule, tsPackage: TSPackage) { const backupDir = path.join(tsPackage.packageDir, BACKUP_DIRNAME); if (tsModule.patchVersion) throw new Error(`Cannot backup an already patched module. You may need to reinstall typescript.`) try { mkdirIfNotExist(backupDir) } catch (e) { throw new BackupError(tsModule.filename, `Couldn't create backup directory. ${e.message}`); } if (shell.cp(tsModule.file, backupDir) && shell.error()) throw new BackupError(tsModule.filename, shell.error()); if (tsModule.filename === 'typescript.js') if (shell.cp(path.join(tsModule.dir, 'typescript.d.ts'), backupDir) && shell.error()) throw new BackupError('typescript.d.ts', shell.error()); } /** * Restore module from backup */ function restore(currentModule: TSModule, tsPackage: TSPackage, noDelete?: boolean) { const copyOrMove = (fileName: string, dest: string) => shell[noDelete ? 'cp' : 'mv'](fileName, dest); const backupDir = path.join(tsPackage.packageDir, BACKUP_DIRNAME); const { file, filename, canPatch, patchVersion, dir } = getTSModule(path.join(backupDir, currentModule.filename)); /* Verify backup file */ if (!canPatch) throw new RestoreError(filename, `Backup file is not a valid typescript module!`); if (patchVersion) throw new RestoreError(filename, `Backup file is not an un-patched ts module`); /* Restore files */ if (copyOrMove(file, tsPackage.libDir) && shell.error()) throw new RestoreError(filename, `Couldn't restore file - ${shell.error()}`); if (filename === 'typescript.js') if (copyOrMove(path.join(dir, 'typescript.d.ts'), tsPackage.libDir) && shell.error()) throw new RestoreError(filename, `Couldn't restore file - ${shell.error()}`); /* Verify restored file */ const restoredModule = getTSModule(currentModule.file); if (!restoredModule.canPatch) throw new RestoreError(filename, `Restored file is not a valid typescript module! You will need to reinstall typescript.` ); if (restoredModule.patchVersion) throw new RestoreError(filename, `Restored file still has patch! You will need to reinstall typescript.` ); // Remove backup dir if empty if ((fs.readdirSync(backupDir).length < 1) && shell.rm('-rf', backupDir) && shell.error()) Log([ '!', `Error deleting backup directory` + chalk.grey(`[${backupDir}]`) ], Log.verbose); } // endregion /* ******************************************************************************************************************** * Actions * ********************************************************************************************************************/ // region Actions /** * Set app options (superimposes opts onto defaultOptions) */ export const setOptions = (opts?: Partial<TSPOptions>) => resetOptions(opts); /** * Patch TypeScript modules */ export function install(opts?: Partial<TSPOptions>) { const ret = patch(defaultInstallLibraries, opts); if (ret) Log([ '+', chalk.green(`ts-patch installed!`) ]); return ret; } /** * Remove patches from TypeScript modules */ export function uninstall(opts?: Partial<TSPOptions>) { const ret = unpatch(defaultInstallLibraries, opts); if (ret) Log([ '-', chalk.green(`ts-patch removed!`) ]); return ret; } /** * Check if files can be patched */ export function check(fileOrFilesOrGlob: string | string[] = SRC_FILES, opts?: Partial<TSPOptions>) { const { basedir } = parseOptions(opts); const { libDir, packageDir, version } = getTSPackage(basedir); Log(`Checking TypeScript ${chalk.blueBright(`v${version}`)} installation in ${chalk.blueBright(packageDir)}\r\n`); const modules = parseFiles(fileOrFilesOrGlob, libDir); for (const module of modules) { const { filename, patchVersion, canPatch, outOfDate } = module; if (patchVersion) Log([ '+', `${chalk.blueBright(filename)} is patched with ts-patch version ` + `${chalk[outOfDate ? 'redBright' : 'blueBright'](patchVersion)} ${outOfDate ? '(out of date)' : '' }` ]); else if (canPatch) Log([ '-', `${chalk.blueBright(filename)} is not patched.` ]); else Log([ '-', chalk.red(`${chalk.redBright(filename)} is not patched and cannot be patched!`) ]); Log('', Log.verbose); } return modules; } /** * Patch a TypeScript module */ export function patch(fileOrFilesOrGlob: string | string[], opts?: Partial<TSPOptions>) { if (!fileOrFilesOrGlob) throw new PatchError(`Must provide a file path, array of files, or glob.`); const { basedir } = parseOptions(opts); const tsPackage = getTSPackage(basedir); const modules = parseFiles(fileOrFilesOrGlob, tsPackage.libDir, true); if (!modules.canUpdateOrPatch.length) { Log([ '!', `File${modules.length-1 ? 's' : ''} already patched with the latest version. For details, run: ` + chalk.bgBlackBright('ts-patch check') ]); return false; } /* Patch files */ for (let m of modules.canUpdateOrPatch) { const { file, filename } = m; Log([ '~', `Patching ${chalk.blueBright(filename)} in ${chalk.blueBright(path.dirname(file))}` ], Log.verbose); // If already patched, load backup module source. Otherwise, backup un-patched if (m.patchVersion) m.moduleSrc = getTSModule(path.join(tsPackage.packageDir, BACKUP_DIRNAME, m.filename), /* includeSrc */ true).moduleSrc; else backup(m, tsPackage); patchTSModule(m, tsPackage); tsPackage.config.modules[filename] = fs.statSync(file).mtimeMs; Log([ '+', chalk.green(`Successfully patched ${chalk.bold.yellow(filename)}.\r\n`) ], Log.verbose); } tsPackage.config.save(); if (modules.unPatchable.length > 1) { Log([ '!', `Some files can't be patched! Try updating to a newer version of ts-patch. The following files are unable to be ` + `patched. [${modules.unPatchable.map(f => f.filename).join(', ')}]` ]); return false; } return true; } export function unpatch(fileOrFilesOrGlob: string | string[], opts?: Partial<TSPOptions>) { if (!fileOrFilesOrGlob) throw new PatchError(`Must provide a file path, array of files, or glob.`); const { basedir, verbose, instanceIsCLI } = parseOptions(opts); const tsPackage = getTSPackage(basedir); const modules = parseFiles(fileOrFilesOrGlob, tsPackage.libDir, true); if (modules.patched.length < 1) { Log([ '!', `File${modules.length-1 ? 's' : ''} not patched. For details, run: ` + chalk.bgBlackBright('ts-patch check') ]); return false; } /* Restore files */ const errors: Record<string, Error> = {}; for (let tsModule of modules.patched) { const { file, filename } = tsModule; Log([ '~', `Restoring ${chalk.blueBright(filename)} in ${chalk.blueBright(path.dirname(file))}` ], Log.verbose); try { restore(tsModule, tsPackage); delete tsPackage.config.modules[filename]; Log([ '+', chalk.green(`Successfully restored ${chalk.bold.yellow(filename)}.\r\n`) ], Log.verbose); } catch (e) { errors[filename] = e; } } /* Save config, or handle if no patched files left */ if (Object.keys(tsPackage.config.modules).length > 0) tsPackage.config.save(); else { // Remove ts-patch.json file shell.rm('-rf', tsPackage.config.file); } /* Handle errors */ if (Object.keys(errors).length > 0) { Object.values(errors).forEach(e => { if (!instanceIsCLI) console.warn(e); else Log([ '!', e.message ], Log.verbose) }); Log(''); throw new RestoreError( `[${Object.keys(errors).join(', ')}]`, 'Try reinstalling typescript.' + (!verbose ? ' (Or, run uninstall again with --verbose for specific error detail)' : '') ); } return true; } /** * Enable persistence hooks */ export function enablePersistence(opts?: Partial<TSPOptions>) { const { basedir } = parseOptions(opts); const { config, packageDir } = getTSPackage(basedir); Log([ '~', `Enabling persistence in ${chalk.blueBright(packageDir)}` ], Log.verbose); config.persist = true; config.save(); /* Copy hooks */ const hooksDir = path.join(packageDir, '../.hooks'); const hooksFiles = HOOKS_FILES.map(f => path.join(RESOURCES_PATH, f)); try { mkdirIfNotExist(hooksDir) } catch (e) { throw new PersistenceError(`Could not create hooks directory in node_modules: ${e.message}`); } if (shell.cp(hooksFiles, hooksDir) && shell.error()) throw new PersistenceError(`Error trying to copy persistence hooks: ${shell.error()}`); /* Write absolute path to ts-patch in hooks */ let tspPath; try { tspPath = path.dirname(resolve.sync('ts-patch/package.json', { basedir: packageDir })) } catch (e) { } if (tspPath) for (let file of hooksFiles.map(f => path.join(hooksDir, path.basename(f)))) { shell.sed('-i', /(?<=^(@SET\s)?tspdir\s*=\s*").+?(?="$)/m, tspPath.split(path.sep).join((path.extname(file) === '.cmd') ? '\\' : '/'), file ); if (shell.error()) throw new PersistenceError(`Error writing to hooks file '${path.basename(file)}': ${shell.error()}`); } Log([ '+', chalk.green(`Enabled persistence for ${chalk.blueBright(packageDir)}`) ]); } /** * Disable persistence hooks */ export function disablePersistence(opts?: Partial<TSPOptions>) { const { basedir } = parseOptions(opts); const { config, packageDir } = getTSPackage(basedir); Log([ '~', `Disabling persistence in ${chalk.blueBright(packageDir)}` ], Log.verbose); config.persist = false; config.save(); /* Remove hooks */ const hooksDir = path.join(packageDir, '../.hooks'); const hooksFiles = HOOKS_FILES.map(f => path.join(hooksDir, f)); if (shell.rm('-rf', hooksFiles) && shell.error()) throw new PersistenceError(`Error trying to remove persistence hooks: ${shell.error()}`); Log([ '-', chalk.green(`Disabled persistence for ${chalk.blueBright(packageDir)}`) ]); } // endregion
the_stack
/* eslint-disable */ import * as jspb from "google-protobuf"; export class ComposeUpRequest extends jspb.Message { getProjectname(): string; setProjectname(value: string): ComposeUpRequest; getWorkdir(): string; setWorkdir(value: string): ComposeUpRequest; clearFilesList(): void; getFilesList(): Array<string>; setFilesList(value: Array<string>): ComposeUpRequest; addFiles(value: string, index?: number): string; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): ComposeUpRequest.AsObject; static toObject(includeInstance: boolean, msg: ComposeUpRequest): ComposeUpRequest.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: ComposeUpRequest, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): ComposeUpRequest; static deserializeBinaryFromReader(message: ComposeUpRequest, reader: jspb.BinaryReader): ComposeUpRequest; } export namespace ComposeUpRequest { export type AsObject = { projectname: string, workdir: string, filesList: Array<string>, } } export class ComposeUpResponse extends jspb.Message { getProjectname(): string; setProjectname(value: string): ComposeUpResponse; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): ComposeUpResponse.AsObject; static toObject(includeInstance: boolean, msg: ComposeUpResponse): ComposeUpResponse.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: ComposeUpResponse, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): ComposeUpResponse; static deserializeBinaryFromReader(message: ComposeUpResponse, reader: jspb.BinaryReader): ComposeUpResponse; } export namespace ComposeUpResponse { export type AsObject = { projectname: string, } } export class ComposeDownRequest extends jspb.Message { getProjectname(): string; setProjectname(value: string): ComposeDownRequest; getWorkdir(): string; setWorkdir(value: string): ComposeDownRequest; clearFilesList(): void; getFilesList(): Array<string>; setFilesList(value: Array<string>): ComposeDownRequest; addFiles(value: string, index?: number): string; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): ComposeDownRequest.AsObject; static toObject(includeInstance: boolean, msg: ComposeDownRequest): ComposeDownRequest.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: ComposeDownRequest, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): ComposeDownRequest; static deserializeBinaryFromReader(message: ComposeDownRequest, reader: jspb.BinaryReader): ComposeDownRequest; } export namespace ComposeDownRequest { export type AsObject = { projectname: string, workdir: string, filesList: Array<string>, } } export class ComposeDownResponse extends jspb.Message { getProjectname(): string; setProjectname(value: string): ComposeDownResponse; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): ComposeDownResponse.AsObject; static toObject(includeInstance: boolean, msg: ComposeDownResponse): ComposeDownResponse.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: ComposeDownResponse, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): ComposeDownResponse; static deserializeBinaryFromReader(message: ComposeDownResponse, reader: jspb.BinaryReader): ComposeDownResponse; } export namespace ComposeDownResponse { export type AsObject = { projectname: string, } } export class ComposeStacksRequest extends jspb.Message { getProjectname(): string; setProjectname(value: string): ComposeStacksRequest; getAll(): boolean; setAll(value: boolean): ComposeStacksRequest; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): ComposeStacksRequest.AsObject; static toObject(includeInstance: boolean, msg: ComposeStacksRequest): ComposeStacksRequest.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: ComposeStacksRequest, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): ComposeStacksRequest; static deserializeBinaryFromReader(message: ComposeStacksRequest, reader: jspb.BinaryReader): ComposeStacksRequest; } export namespace ComposeStacksRequest { export type AsObject = { projectname: string, all: boolean, } } export class ComposeStacksResponse extends jspb.Message { clearStacksList(): void; getStacksList(): Array<Stack>; setStacksList(value: Array<Stack>): ComposeStacksResponse; addStacks(value?: Stack, index?: number): Stack; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): ComposeStacksResponse.AsObject; static toObject(includeInstance: boolean, msg: ComposeStacksResponse): ComposeStacksResponse.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: ComposeStacksResponse, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): ComposeStacksResponse; static deserializeBinaryFromReader(message: ComposeStacksResponse, reader: jspb.BinaryReader): ComposeStacksResponse; } export namespace ComposeStacksResponse { export type AsObject = { stacksList: Array<Stack.AsObject>, } } export class Stack extends jspb.Message { getId(): string; setId(value: string): Stack; getName(): string; setName(value: string): Stack; getStatus(): string; setStatus(value: string): Stack; getReason(): string; setReason(value: string): Stack; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): Stack.AsObject; static toObject(includeInstance: boolean, msg: Stack): Stack.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: Stack, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): Stack; static deserializeBinaryFromReader(message: Stack, reader: jspb.BinaryReader): Stack; } export namespace Stack { export type AsObject = { id: string, name: string, status: string, reason: string, } } export class ComposeServicesRequest extends jspb.Message { getProjectname(): string; setProjectname(value: string): ComposeServicesRequest; getWorkdir(): string; setWorkdir(value: string): ComposeServicesRequest; clearFilesList(): void; getFilesList(): Array<string>; setFilesList(value: Array<string>): ComposeServicesRequest; addFiles(value: string, index?: number): string; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): ComposeServicesRequest.AsObject; static toObject(includeInstance: boolean, msg: ComposeServicesRequest): ComposeServicesRequest.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: ComposeServicesRequest, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): ComposeServicesRequest; static deserializeBinaryFromReader(message: ComposeServicesRequest, reader: jspb.BinaryReader): ComposeServicesRequest; } export namespace ComposeServicesRequest { export type AsObject = { projectname: string, workdir: string, filesList: Array<string>, } } export class ComposeServicesResponse extends jspb.Message { clearServicesList(): void; getServicesList(): Array<Service>; setServicesList(value: Array<Service>): ComposeServicesResponse; addServices(value?: Service, index?: number): Service; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): ComposeServicesResponse.AsObject; static toObject(includeInstance: boolean, msg: ComposeServicesResponse): ComposeServicesResponse.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: ComposeServicesResponse, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): ComposeServicesResponse; static deserializeBinaryFromReader(message: ComposeServicesResponse, reader: jspb.BinaryReader): ComposeServicesResponse; } export namespace ComposeServicesResponse { export type AsObject = { servicesList: Array<Service.AsObject>, } } export class Service extends jspb.Message { getId(): string; setId(value: string): Service; getName(): string; setName(value: string): Service; getReplicas(): number; setReplicas(value: number): Service; getDesired(): number; setDesired(value: number): Service; clearPortsList(): void; getPortsList(): Array<string>; setPortsList(value: Array<string>): Service; addPorts(value: string, index?: number): string; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): Service.AsObject; static toObject(includeInstance: boolean, msg: Service): Service.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: Service, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): Service; static deserializeBinaryFromReader(message: Service, reader: jspb.BinaryReader): Service; } export namespace Service { export type AsObject = { id: string, name: string, replicas: number, desired: number, portsList: Array<string>, } }
the_stack
import { logger } from './logger'; import AWS from 'aws-sdk'; import _ from 'lodash'; import { SUPPORTED_SERVICES, AWSSegmentParsers } from './aws-segments/index'; import BBPromise from 'bluebird'; import { IamPolicyDocument, IamStatement } from './aws-segments/iam-policy'; import crypto from 'crypto'; import fs from 'fs'; import {Trace} from 'aws-sdk/clients/xray'; import { IamPolicyUtils } from './iam-policy-utils'; const DEF_TIME_RANGE = 60; export const EXCESSIVE_PERMISSION_FILE = 'excessive_permissions.json'; export interface ScanXrayTracesConf { /** * start time to search for. If not specified will do a "last x min search" */ startTime?: Date; /** * Time in minutes range to search. If startTime is not specified this will be used as a last X min search. * Defaults to: 60 */ timeRangeMinutes?: number; /** * Filter expression as documented at: https://docs.aws.amazon.com/xray/latest/devguide/xray-console-filters.html#console-filters-syntax */ filterExpression?: string; /** * Perform comparison against the application role and generate an excess permissions report */ compareExistingRole?: boolean; } /** * Fetch xray traces. Combines the two functions of getTraceSummaries and batchGetTraces including support for pagination. */ export async function getXrayTraces(conf?: ScanXrayTracesConf) { try { logger.info('getXrayTraces: params: ', conf); const xray = new AWS.XRay(); const timeRangeMS = ((conf && conf.timeRangeMinutes) || DEF_TIME_RANGE) * 60 * 1000; const StartTime = (conf && conf.startTime) || new Date(Date.now() - timeRangeMS); const EndTime = new Date(StartTime.getTime() + timeRangeMS); logger.info("GetTraceSummariesRequest: StarTime: %s, EndTime: %s", StartTime, EndTime); const summariesParams: AWS.XRay.Types.GetTraceSummariesRequest = { StartTime, EndTime, FilterExpression: (conf && conf.filterExpression) || undefined, }; let paginationNum = 0; let nextToken: string | undefined; let summaries: AWS.XRay.TraceSummary[] = []; do { summariesParams.NextToken = nextToken; const traceSummariesResp = await xray.getTraceSummaries(summariesParams).promise(); logger.debug('getTraceSummaries [token: %s] result: ', nextToken, traceSummariesResp); if(traceSummariesResp.TraceSummaries) { summaries = summaries.concat(traceSummariesResp.TraceSummaries); } nextToken = traceSummariesResp.NextToken; paginationNum++; } while (nextToken); logger.info('getTraceSummaries total summaries after [%s] pagination: ', paginationNum, summaries.length); let batchNum = 0; let ids: string[] = []; // tslint:disable-next-line:max-line-length const batchResults = await BBPromise.map<AWS.XRay.TraceSummary, AWS.XRay.BatchGetTracesResult | null>(summaries, (trace, index, arrayLength) => { if (trace.Id) { ids.push(trace.Id); } //aws enforces max 5 ids in a batch. We do the request when we reach 5 or on the last index if (ids.length === 5 || index === (arrayLength - 1)) { logger.debug('Performing batchGetTraces with ids: ', ids); const res = xray.batchGetTraces({ TraceIds: ids }).promise(); ids = []; batchNum++; return res; } return null; }, { concurrency: 10 }); let traces: Trace[] = []; for (const res of batchResults) { if (res) { logger.debug("batchGetTraces result: ", res); if (!_.isEmpty(res.Traces)) { logger.debug('batchGetTraces count: ', res.Traces!.length); traces = traces.concat(res.Traces!); } else { logger.error('Got empty result from batchGetTraces for ids: ', ids); } } } logger.info('getXrayTraces total traces returned: %s, number of batches: %s', traces.length, batchNum); return traces; } catch (error) { logger.error("Failed fetching traces: ", error); throw error; } } /** * Map that maps a resource to set of actions */ export class ResourceActionMap extends Map<string, Set<string>> { constructor() { super(); } addActionToResource(actionOp: string, resourceArn: string) { let actions = super.get(resourceArn); if(!actions) { actions = new Set(); super.set(resourceArn, actions); } actions.add(actionOp); } } /** * Map which maps a function to the set of ResourceActionMap */ export type FunctionToActionsMap = Map<string, ResourceActionMap>; function parseSegmentDoc(doc: any, functionMap: FunctionToActionsMap, parentActionsMap?: ResourceActionMap, functionArn?: string) { //if this is a subsegment we will want to add to the parentActionsMap if this relates to an aws service if (parentActionsMap && doc.namespace === 'aws' && SUPPORTED_SERVICES.indexOf(doc.name) >= 0) { AWSSegmentParsers[doc.name](doc, parentActionsMap, functionArn!); } //see if this is a Lambda function. If so it will have aws.function_arn const arn = _.get(doc, 'aws.function_arn'); let actionsMap: ResourceActionMap | undefined = parentActionsMap; if (arn) { logger.debug('Found arn: %s for Segment: %s', arn, doc.id); actionsMap = functionMap.get(arn); if (!actionsMap) { actionsMap = new ResourceActionMap(); functionMap.set(arn, actionsMap); } } if (!_.isEmpty(doc.subsegments)) { for (const subsegment of doc.subsegments) { parseSegmentDoc(subsegment, functionMap, actionsMap, arn); } } } /** * Parse an xray trace return the passed in functionMap * @param trace * @param functionMap will populate with the found results */ export function parseXrayTrace(trace: AWS.XRay.Trace, functionMap: FunctionToActionsMap): FunctionToActionsMap { if (_.isEmpty(trace.Segments)) { logger.info('No segments found for TraceId: ', trace.Id); return functionMap; } //we search for lambda segments and then follow into sub segments for (const segment of trace.Segments!) { const docStr = segment.Document; if (_.isEmpty(docStr)) { logger.warn("Got segment [id: %s] with empty Document.", segment.Id); } else { parseSegmentDoc(JSON.parse(docStr!), functionMap); } } return functionMap; } export function parseXrayTraces(traces: AWS.XRay.Trace[], functionMap: FunctionToActionsMap): FunctionToActionsMap { if (_.isEmpty(traces)) { return functionMap; } for (const trace of traces) { parseXrayTrace(trace, functionMap); } return functionMap; } export async function getFunctionActionMapFromXray(conf?: ScanXrayTracesConf) { const traces = await getXrayTraces(conf); const map: FunctionToActionsMap = new Map(); return parseXrayTraces(traces, map); } export function createIAMPolicyDoc(map: ResourceActionMap, functionArn: string) { const doc: IamPolicyDocument = { Version: "2012-10-17", Description: "Generated policy from xray scan for: " + functionArn, Statement: [], }; //consolidate resources with the same functions into one entry const actionMap = new Map<string, {resources: string[], actions: string[]}>(); for (const entry of map.entries()) { const match = entry[0].match(/arn:aws:(.+?):/); let service = ''; if(!match || match.length < 2) { logger.error("Couldn't extract service name from resource arn: ", entry[0]); } else { service = match[1]; } const actions = Array.from(entry[1], (s) => `${service}:${s}`).sort(); const actionsKey = actions.join(); let actionMapEntry = actionMap.get(actionsKey); if(!actionMapEntry) { actionMapEntry = { resources: [], actions, }; actionMap.set(actionsKey, actionMapEntry); } actionMapEntry.resources.push(entry[0]); } for (const val of actionMap.values()) { const stm: IamStatement = { Effect: "Allow", Action: val.actions, Resource: val.resources, }; doc.Statement!.push(stm); } if(_.isEmpty(doc.Statement)) { //append more details in the description // tslint:disable-next-line:max-line-length doc.Description += ". Note: No access to AWS resources were found for this function. It may be that X-Ray wasn't configured correctly. See: https://github.com/functionalone/aws-least-privilege#x-ray-setup on how to setup X-Ray."; } return doc; } export interface AppExcessPermissions { arn: string; role: string; excessPermissions: IamStatement[]; } export async function compareLambdaRoleToPolicy(lambdaArn: string, policy: IamPolicyDocument) { const iamUtils = new IamPolicyUtils(); if(!policy.Statement) { return; } const lambda = new AWS.Lambda(); const config = await lambda.getFunctionConfiguration({FunctionName: lambdaArn}).promise(); if(config.Role) { const roleName = config.Role.substr(config.Role.lastIndexOf('/') + 1); const roleStatements = await iamUtils.getCombinedStatementsForRole(roleName); const excessStatements = iamUtils.checkExcessPolicyPermissions(roleStatements, policy.Statement); if(!_.isEmpty(excessStatements)) { const res: AppExcessPermissions = { arn: lambdaArn, role: config.Role, excessPermissions: excessStatements!, }; return res; } } } export interface GeneratedPolicy { Arn: string; FileName?: string; Policy: IamPolicyDocument; } export interface ScanResult { GeneratedPolicies: GeneratedPolicy[]; ExcessPermissions: AppExcessPermissions[]; } /** * Will scan xray and return a ScanResult * @param conf */ export async function scanXray(conf: ScanXrayTracesConf): Promise<ScanResult> { const map: FunctionToActionsMap = await getFunctionActionMapFromXray(conf); const res: ScanResult = { GeneratedPolicies: [], ExcessPermissions: [], }; const promiseArr: Promise<AppExcessPermissions|undefined>[] = []; for (const entry of map.entries()) { const policyDoc = createIAMPolicyDoc(entry[1], entry[0]); res.GeneratedPolicies.push({ Arn: entry[0], Policy: policyDoc, }); if(conf.compareExistingRole) { promiseArr.push(compareLambdaRoleToPolicy(entry[0], policyDoc)); } } if(conf.compareExistingRole) { const permissionsRes = await Promise.all(promiseArr); for (const perm of permissionsRes) { if(perm) { res.ExcessPermissions.push(perm); } } } return res; } /** * * @param conf * @return object mapping function arn to file name */ export async function scanXrayAndSaveFiles(conf: ScanXrayTracesConf) { const res = await scanXray(conf); for (const generatedPolicy of res.GeneratedPolicies) { const hash = crypto.createHash('md5'); hash.update(generatedPolicy.Arn); const fileName = hash.digest('hex') + ".policy.json"; generatedPolicy.FileName = fileName; try { fs.writeFileSync(fileName, JSON.stringify(generatedPolicy.Policy, undefined, 2)); } catch (error) { logger.error("Failed writing to file: [%s] ",fileName, error); } } if(!_.isEmpty(res.ExcessPermissions)) { fs.writeFileSync(EXCESSIVE_PERMISSION_FILE, JSON.stringify(res.ExcessPermissions, undefined, 2)); } return res; } // export XRay.Trace;
the_stack
import { AsnConvert } from "@peculiar/asn1-schema"; import { JsonParser, JsonSerializer } from "@peculiar/json-schema"; import { BufferSourceConverter, Convert } from "pvtsutils"; import * as core from "webcrypto-core"; import { Debug } from "./debug"; import { Browser, BrowserInfo } from "./helper"; import { CryptoKey } from "./key"; import { AesCbcProvider, AesCtrProvider, AesEcbProvider, AesGcmProvider, AesKwProvider, DesCbcProvider, DesEde3CbcProvider, EcCrypto, EcdhProvider, EcdsaProvider, HmacProvider, Pbkdf2Provider, RsaEsProvider, RsaOaepProvider, RsaPssProvider, RsaSsaProvider, Sha1Provider, Sha256Provider, Sha512Provider, EdDsaProvider, EcdhEsProvider, } from "./mechs"; import { getOidByNamedCurve } from "./mechs/ec/helper"; import { nativeSubtle } from "./native"; import { WrappedNativeCryptoKey } from "./wrapped_native_key"; type SubtleMethods = keyof core.SubtleCrypto; export class SubtleCrypto extends core.SubtleCrypto { private static readonly methods: SubtleMethods[] = ["digest", "importKey", "exportKey", "sign", "verify", "generateKey", "encrypt", "decrypt", "deriveBits", "deriveKey", "wrapKey", "unwrapKey"]; /** * Returns true if key is CryptoKey and is not liner key * > WARN Some browsers doesn't have CryptKey class in `self`. * @param key */ private static isAnotherKey(key: any): key is core.NativeCryptoKey { if (typeof key === "object" && typeof key.type === "string" && typeof key.extractable === "boolean" && typeof key.algorithm === "object") { return !(key instanceof CryptoKey); } return false; } public readonly browserInfo = BrowserInfo(); public constructor() { super(); //#region AES this.providers.set(new AesCbcProvider()); this.providers.set(new AesCtrProvider()); this.providers.set(new AesEcbProvider()); this.providers.set(new AesGcmProvider()); this.providers.set(new AesKwProvider()); //#endregion //#region DES this.providers.set(new DesCbcProvider()); this.providers.set(new DesEde3CbcProvider()); //#endregion //#region RSA this.providers.set(new RsaSsaProvider()); this.providers.set(new RsaPssProvider()); this.providers.set(new RsaOaepProvider()); this.providers.set(new RsaEsProvider()); //#endregion //#region EC this.providers.set(new EcdsaProvider()); this.providers.set(new EcdhProvider()); //#endregion //#region SHA this.providers.set(new Sha1Provider()); this.providers.set(new Sha256Provider()); this.providers.set(new Sha512Provider()); //#endregion //#region PBKDF this.providers.set(new Pbkdf2Provider()); //#endregion //#region HMAC this.providers.set(new HmacProvider()); //#endregion //#region EdDSA this.providers.set(new EdDsaProvider()); //#endregion //#region ECDH-ES // TODO Elliptic.js has got issue (https://github.com/indutny/elliptic/issues/243). Uncomment the next line after fix // this.providers.set(new EcdhEsProvider()); //#endregion } public async digest(...args: any[]) { return this.wrapNative("digest", ...args); } public async importKey(...args: any[]) { this.fixFirefoxEcImportPkcs8(args); return this.wrapNative("importKey", ...args); } public async exportKey(...args: any[]) { return await this.fixFirefoxEcExportPkcs8(args) || await this.wrapNative("exportKey", ...args); } public async generateKey(...args: any[]) { return this.wrapNative("generateKey", ...args); } public async sign(...args: any[]) { return this.wrapNative("sign", ...args); } public async verify(...args: any[]) { return this.wrapNative("verify", ...args); } public async encrypt(...args: any[]) { return this.wrapNative("encrypt", ...args); } public async decrypt(...args: any[]) { return this.wrapNative("decrypt", ...args); } public async wrapKey(...args: any[]) { return this.wrapNative("wrapKey", ...args); } public async unwrapKey(...args: any[]) { return this.wrapNative("unwrapKey", ...args); } public async deriveBits(...args: any[]) { return this.wrapNative("deriveBits", ...args); } public async deriveKey(...args: any[]) { return this.wrapNative("deriveKey", ...args); } private async wrapNative(method: SubtleMethods, ...args: any[]) { if (~["generateKey", "unwrapKey", "deriveKey", "importKey"].indexOf(method)) { this.fixAlgorithmName(args); } try { if (method !== "digest" || !args.some((a) => a instanceof CryptoKey)) { const nativeArgs = this.fixNativeArguments(method, args); Debug.info(`Call native '${method}' method`, nativeArgs); const res = await nativeSubtle[method].apply(nativeSubtle, nativeArgs); return this.fixNativeResult(method, args, res); } } catch (e) { Debug.warn(`Error on native '${method}' calling. ${e.message}`, e); } if (method === "wrapKey") { try { Debug.info(`Trying to wrap key by using native functions`, args); // wrapKey(format, key, wrappingKey, wrapAlgorithm); // indexes 0 1 2 3 const data = await this.exportKey(args[0], args[1]); const keyData = (args[0] === "jwk") ? Convert.FromUtf8String(JSON.stringify(data)) : data; const res = await this.encrypt(args[3], args[2], keyData); return res; } catch (e) { Debug.warn(`Cannot wrap key by native functions. ${e.message}`, e); } } if (method === "unwrapKey") { try { Debug.info(`Trying to unwrap key by using native functions`, args); // unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages); // indexes 0 1 2 3 4 5 6 const data = await this.decrypt(args[3], args[2], args[1]); const keyData = (args[0] === "jwk") ? JSON.parse(Convert.ToUtf8String(data)) : data; const res = await this.importKey(args[0], keyData, args[4], args[5], args[6]); return res; } catch (e) { Debug.warn(`Cannot unwrap key by native functions. ${e.message}`, e); } } if (method === "deriveKey") { try { Debug.info(`Trying to derive key by using native functions`, args); const data = await this.deriveBits(args[0], args[1], args[2].length); const res = await this.importKey("raw", data, args[2], args[3], args[4]); return res; } catch (e) { Debug.warn(`Cannot derive key by native functions. ${e.message}`, e); } } if (method === "deriveBits" || method === "deriveKey") { // Cast public keys from algorithm for (const arg of args) { if (typeof arg === "object" && arg.public && SubtleCrypto.isAnotherKey(arg.public)) { arg.public = await this.castKey(arg.public); } } } // Cast native keys to liner keys for (let i = 0; i < args.length; i++) { const arg = args[i]; if (SubtleCrypto.isAnotherKey(arg)) { args[i] = await this.castKey(arg); } } return super[method].apply(this, args); } private fixNativeArguments(method: SubtleMethods, args: any[]) { const res = [...args]; if (method === "importKey") { if (this.browserInfo.name === Browser.IE && res[0]?.toLowerCase?.() === "jwk" && !BufferSourceConverter.isBufferSource(res[1])) { // IE11 uses ArrayBuffer instead of JSON object res[1] = Convert.FromUtf8String(JSON.stringify(res[1])); } } if (this.browserInfo.name === Browser.IE && args[1] instanceof WrappedNativeCryptoKey) { // Fix algs for IE11 switch (method) { case "sign": case "verify": case "encrypt": case "decrypt": res[0] = { ...this.prepareAlgorithm(res[0]), hash: (res[1]?.algorithm as RsaHashedKeyAlgorithm)?.hash?.name }; break; case "wrapKey": case "unwrapKey": res[4] = { ...this.prepareAlgorithm(res[4]), hash: (res[3]?.algorithm as RsaHashedKeyAlgorithm)?.hash?.name }; break; } } for (let i = 0; i < res.length; i++) { const arg = res[i]; if (arg instanceof WrappedNativeCryptoKey) { // Convert wrapped key to Native CryptoKey res[i] = arg.getNative(); } } return res; } private fixNativeResult(method: SubtleMethods, args: any[], res: any): any { if (this.browserInfo.name === Browser.IE) { if (method === "exportKey") { if (args[0]?.toLowerCase?.() === "jwk" && res instanceof ArrayBuffer) { // IE11 uses ArrayBuffer instead of JSON object return JSON.parse(Convert.ToUtf8String(res)); } } // wrap IE11 native key if ("privateKey" in res) { const privateKeyUsages = ["sign", "decrypt", "unwrapKey", "deriveKey", "deriveBits"]; const publicKeyUsages = ["verify", "encrypt", "wrapKey"]; return { privateKey: this.wrapNativeKey(res.privateKey, args[0], args[1], args[2].filter((o: string) => privateKeyUsages.includes(o))), publicKey: this.wrapNativeKey(res.publicKey, args[0], args[1], args[2].filter((o: string) => publicKeyUsages.includes(o))), }; } else if ("extractable" in res) { let algorithm: Algorithm; let usages: KeyUsage[]; switch (method) { case "importKey": algorithm = args[2]; usages = args[4]; break; case "unwrapKey": algorithm = args[4]; usages = args[6]; break; case "generateKey": algorithm = args[0]; usages = args[2]; break; default: throw new core.OperationError("Cannot wrap native key. Unsupported method in use"); } return this.wrapNativeKey(res, algorithm, res.extractable, usages); } } return res; } private wrapNativeKey(key: core.NativeCryptoKey, algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): core.NativeCryptoKey { if (this.browserInfo.name === Browser.IE) { const algs = [ "RSASSA-PKCS1-v1_5", "RSA-PSS", "RSA-OAEP", "AES-CBC", "AES-CTR", "AES-KW", "HMAC", ]; const index = algs.map((o) => o.toLowerCase()).indexOf(key.algorithm.name.toLowerCase()); if (index !== -1) { const alg = this.prepareAlgorithm(algorithm); const newAlg: any = { ...key.algorithm, name: algs[index], }; if (core.SubtleCrypto.isHashedAlgorithm(alg)) { newAlg.hash = { name: (alg.hash as any).name.toUpperCase(), }; } Debug.info(`Wrapping ${algs[index]} crypto key to WrappedNativeCryptoKey`); return new WrappedNativeCryptoKey(newAlg, extractable, key.type, keyUsages, key); } } return key; } private async castKey(key: core.NativeCryptoKey) { Debug.info("Cast native CryptoKey to linter key.", key); if (!key.extractable) { throw new Error("Cannot cast unextractable crypto key"); } const provider = this.getProvider(key.algorithm.name); const jwk = await this.exportKey("jwk", key); return provider.importKey("jwk", jwk, key.algorithm, true, key.usages); } /** * Fixes name of the algorithms. Edge doesn't normilize algorithm names in keys * @param args */ private fixAlgorithmName(args: any[]) { if (this.browserInfo.name === Browser.Edge) { for (let i = 0; i < args.length; i++) { const arg = args[0]; if (typeof arg === "string") { // algorithm for (const algorithm of this.providers.algorithms) { if (algorithm.toLowerCase() === arg.toLowerCase()) { args[i] = algorithm; break; } } } else if (typeof arg === "object" && typeof arg.name === "string") { // algorithm.name for (const algorithm of this.providers.algorithms) { if (algorithm.toLowerCase() === arg.name.toLowerCase()) { arg.name = algorithm; } if ((typeof arg.hash === "string" && algorithm.toLowerCase() === arg.hash.toLowerCase()) || (typeof arg.hash === "object" && typeof arg.hash.name === "string" && algorithm.toLowerCase() === arg.hash.name.toLowerCase())) { arg.hash = { name: algorithm }; } } } } } } /** * Firefox doesn't support import PKCS8 key for ECDSA/ECDH */ private fixFirefoxEcImportPkcs8(args: any[]) { const preparedAlgorithm = this.prepareAlgorithm(args[2]) as EcKeyImportParams; const algName = preparedAlgorithm.name.toUpperCase(); if (this.browserInfo.name === Browser.Firefox && args[0] === "pkcs8" && ~["ECDSA", "ECDH"].indexOf(algName) && ~["P-256", "P-384", "P-521"].indexOf(preparedAlgorithm.namedCurve)) { if (!core.BufferSourceConverter.isBufferSource(args[1])) { throw new TypeError("data: Is not ArrayBuffer or ArrayBufferView"); } const preparedData = core.BufferSourceConverter.toArrayBuffer(args[1]); // Convert PKCS8 to JWK const keyInfo = AsnConvert.parse(preparedData, core.asn1.PrivateKeyInfo); const privateKey = AsnConvert.parse(keyInfo.privateKey, core.asn1.EcPrivateKey); const jwk: JsonWebKey = JsonSerializer.toJSON(privateKey); jwk.ext = true; jwk.key_ops = args[4]; jwk.crv = preparedAlgorithm.namedCurve; jwk.kty = "EC"; args[0] = "jwk"; args[1] = jwk; } } /** * Firefox doesn't support export PKCS8 key for ECDSA/ECDH */ private async fixFirefoxEcExportPkcs8(args: any[]) { try { if (this.browserInfo.name === Browser.Firefox && args[0] === "pkcs8" && ~["ECDSA", "ECDH"].indexOf(args[1].algorithm.name) && ~["P-256", "P-384", "P-521"].indexOf(args[1].algorithm.namedCurve)) { const jwk = await this.exportKey("jwk", args[1]); // Convert JWK to PKCS8 const ecKey = JsonParser.fromJSON(jwk, { targetSchema: core.asn1.EcPrivateKey }); const keyInfo = new core.asn1.PrivateKeyInfo(); keyInfo.privateKeyAlgorithm.algorithm = EcCrypto.ASN_ALGORITHM; keyInfo.privateKeyAlgorithm.parameters = AsnConvert.serialize( new core.asn1.ObjectIdentifier(getOidByNamedCurve(args[1].algorithm.namedCurve)), ); keyInfo.privateKey = AsnConvert.serialize(ecKey); return AsnConvert.serialize(keyInfo); } } catch (err) { Debug.error(err); return null; } } }
the_stack
import { BigNumber } from '@ethersproject/bignumber'; import { arrayify, hexlify } from '@ethersproject/bytes'; import { TransactionReceipt } from '@ethersproject/abstract-provider'; import { core } from '@optics-xyz/ts-interface'; import { OpticsContext } from '..'; import { delay } from '../../utils'; import { DispatchEvent, AnnotatedDispatch, AnnotatedUpdate, AnnotatedProcess, UpdateTypes, UpdateArgs, ProcessTypes, ProcessArgs, AnnotatedLifecycleEvent, Annotated, DispatchTypes, } from '../events'; import { queryAnnotatedEvents } from '..'; import { keccak256 } from 'ethers/lib/utils'; export type ParsedMessage = { from: number; sender: string; nonce: number; destination: number; recipient: string; body: string; }; export type OpticsStatus = { status: MessageStatus; events: AnnotatedLifecycleEvent[]; }; export enum MessageStatus { Dispatched = 0, Included = 1, Relayed = 2, Processed = 3, } export enum ReplicaMessageStatus { None = 0, Proven, Processed, } export type EventCache = { homeUpdate?: AnnotatedUpdate; replicaUpdate?: AnnotatedUpdate; process?: AnnotatedProcess; }; /** * Parse a serialized Optics message from raw bytes. * * @param message * @returns */ export function parseMessage(message: string): ParsedMessage { const buf = Buffer.from(arrayify(message)); const from = buf.readUInt32BE(0); const sender = hexlify(buf.slice(4, 36)); const nonce = buf.readUInt32BE(36); const destination = buf.readUInt32BE(40); const recipient = hexlify(buf.slice(44, 76)); const body = hexlify(buf.slice(76)); return { from, sender, nonce, destination, recipient, body }; } /** * A deserialized Optics message. */ export class OpticsMessage { readonly dispatch: AnnotatedDispatch; readonly message: ParsedMessage; readonly home: core.Home; readonly replica: core.Replica; readonly context: OpticsContext; protected cache: EventCache; constructor(context: OpticsContext, dispatch: AnnotatedDispatch) { this.context = context; this.message = parseMessage(dispatch.event.args.message); this.dispatch = dispatch; this.home = context.mustGetCore(this.message.from).home; this.replica = context.mustGetReplicaFor( this.message.from, this.message.destination, ); this.cache = {}; } /** * The receipt of the TX that dispatched this message */ get receipt(): TransactionReceipt { return this.dispatch.receipt; } /** * Instantiate one or more messages from a receipt. * * @param context the {@link OpticsContext} object to use * @param nameOrDomain the domain on which the receipt was logged * @param receipt the receipt * @returns an array of {@link OpticsMessage} objects */ static fromReceipt( context: OpticsContext, nameOrDomain: string | number, receipt: TransactionReceipt, ): OpticsMessage[] { const messages: OpticsMessage[] = []; const home = new core.Home__factory().interface; for (const log of receipt.logs) { try { const parsed = home.parseLog(log); if (parsed.name === 'Dispatch') { const dispatch = parsed as unknown as DispatchEvent; dispatch.getBlock = () => { return context .mustGetProvider(nameOrDomain) .getBlock(log.blockHash); }; dispatch.getTransaction = () => { return context .mustGetProvider(nameOrDomain) .getTransaction(log.transactionHash); }; dispatch.getTransactionReceipt = () => { return context .mustGetProvider(nameOrDomain) .getTransactionReceipt(log.transactionHash); }; const annotated = new Annotated<DispatchTypes, DispatchEvent>( context.resolveDomain(nameOrDomain), receipt, dispatch, true, ); annotated.event.blockNumber = annotated.receipt.blockNumber; const message = new OpticsMessage(context, annotated); messages.push(message); } } catch (e) { continue; } } return messages; } /** * Instantiate EXACTLY one message from a receipt. * * @param context the {@link OpticsContext} object to use * @param nameOrDomain the domain on which the receipt was logged * @param receipt the receipt * @returns an array of {@link OpticsMessage} objects * @throws if there is not EXACTLY 1 dispatch in the receipt */ static singleFromReceipt( context: OpticsContext, nameOrDomain: string | number, receipt: TransactionReceipt, ): OpticsMessage { const messages: OpticsMessage[] = OpticsMessage.fromReceipt( context, nameOrDomain, receipt, ); if (messages.length !== 1) { throw new Error('Expected single Dispatch in transaction'); } return messages[0]; } /** * Instantiate one or more messages from a tx hash. * * @param context the {@link OpticsContext} object to use * @param nameOrDomain the domain on which the receipt was logged * @param receipt the receipt * @returns an array of {@link OpticsMessage} objects * @throws if there is no receipt for the TX */ static async fromTransactionHash( context: OpticsContext, nameOrDomain: string | number, transactionHash: string, ): Promise<OpticsMessage[]> { const provider = context.mustGetProvider(nameOrDomain); const receipt = await provider.getTransactionReceipt(transactionHash); if (!receipt) { throw new Error(`No receipt for ${transactionHash} on ${nameOrDomain}`); } return OpticsMessage.fromReceipt(context, nameOrDomain, receipt); } /** * Instantiate EXACTLY one message from a transaction has. * * @param context the {@link OpticsContext} object to use * @param nameOrDomain the domain on which the receipt was logged * @param receipt the receipt * @returns an array of {@link OpticsMessage} objects * @throws if there is no receipt for the TX, or if not EXACTLY 1 dispatch in * the receipt */ static async singleFromTransactionHash( context: OpticsContext, nameOrDomain: string | number, transactionHash: string, ): Promise<OpticsMessage> { const provider = context.mustGetProvider(nameOrDomain); const receipt = await provider.getTransactionReceipt(transactionHash); if (!receipt) { throw new Error(`No receipt for ${transactionHash} on ${nameOrDomain}`); } return OpticsMessage.singleFromReceipt(context, nameOrDomain, receipt); } /** * Get the Home `Update` event associated with this message (if any) * * @returns An {@link AnnotatedUpdate} (if any) */ async getHomeUpdate(): Promise<AnnotatedUpdate | undefined> { // if we have already gotten the event, // return it without re-querying if (this.cache.homeUpdate) { return this.cache.homeUpdate; } // if not, attempt to query the event const updateFilter = this.home.filters.Update( undefined, this.committedRoot, ); const updateLogs: AnnotatedUpdate[] = await queryAnnotatedEvents< UpdateTypes, UpdateArgs >(this.context, this.origin, this.home, updateFilter); if (updateLogs.length === 1) { // if event is returned, store it to the object this.cache.homeUpdate = updateLogs[0]; } else if (updateLogs.length > 1) { throw new Error('multiple home updates for same root'); } // return the event or undefined if it doesn't exist return this.cache.homeUpdate; } /** * Get the Replica `Update` event associated with this message (if any) * * @returns An {@link AnnotatedUpdate} (if any) */ async getReplicaUpdate(): Promise<AnnotatedUpdate | undefined> { // if we have already gotten the event, // return it without re-querying if (this.cache.replicaUpdate) { return this.cache.replicaUpdate; } // if not, attempt to query the event const updateFilter = this.replica.filters.Update( undefined, this.committedRoot, ); const updateLogs: AnnotatedUpdate[] = await queryAnnotatedEvents< UpdateTypes, UpdateArgs >(this.context, this.destination, this.replica, updateFilter); if (updateLogs.length === 1) { // if event is returned, store it to the object this.cache.replicaUpdate = updateLogs[0]; } else if (updateLogs.length > 1) { throw new Error('multiple replica updates for same root'); } // return the event or undefined if it wasn't found return this.cache.replicaUpdate; } /** * Get the Replica `Process` event associated with this message (if any) * * @returns An {@link AnnotatedProcess} (if any) */ async getProcess(): Promise<AnnotatedProcess | undefined> { // if we have already gotten the event, // return it without re-querying if (this.cache.process) { return this.cache.process; } // if not, attempt to query the event const processFilter = this.replica.filters.Process(this.leaf); const processLogs = await queryAnnotatedEvents<ProcessTypes, ProcessArgs>( this.context, this.destination, this.replica, processFilter, ); if (processLogs.length === 1) { // if event is returned, store it to the object this.cache.process = processLogs[0]; } else if (processLogs.length > 1) { throw new Error('multiple replica process for same message'); } // return the update or undefined if it doesn't exist return this.cache.process; } /** * Get all lifecycle events associated with this message * * @returns An array of {@link AnnotatedLifecycleEvent} objects */ async events(): Promise<OpticsStatus> { const events: AnnotatedLifecycleEvent[] = [this.dispatch]; // attempt to get Home update const homeUpdate = await this.getHomeUpdate(); if (!homeUpdate) { return { status: MessageStatus.Dispatched, // the message has been sent; nothing more events, }; } events.push(homeUpdate); // attempt to get Replica update const replicaUpdate = await this.getReplicaUpdate(); if (!replicaUpdate) { return { status: MessageStatus.Included, // the message was sent, then included in an Update on Home events, }; } events.push(replicaUpdate); // attempt to get Replica process const process = await this.getProcess(); if (!process) { // NOTE: when this is the status, you may way to // query confirmAt() to check if challenge period // on the Replica has elapsed or not return { status: MessageStatus.Relayed, // the message was sent, included in an Update, then relayed to the Replica events, }; } events.push(process); return { status: MessageStatus.Processed, // the message was processed events, }; } /** * Returns the timestamp after which it is possible to process this message. * * Note: return the timestamp after which it is possible to process messages * within an Update. The timestamp is most relevant during the time AFTER the * Update has been Relayed to the Replica and BEFORE the message in question * has been Processed. * * Considerations: * - the timestamp will be 0 if the Update has not been relayed to the Replica * - after the Update has been relayed to the Replica, the timestamp will be * non-zero forever (even after all messages in the Update have been * processed) * - if the timestamp is in the future, the challenge period has not elapsed * yet; messages in the Update cannot be processed yet * - if the timestamp is in the past, this does not necessarily mean that all * messages in the Update have been processed * * @returns The timestamp at which a message can confirm */ async confirmAt(): Promise<BigNumber> { const update = await this.getHomeUpdate(); if (!update) { return BigNumber.from(0); } const { newRoot } = update.event.args; return this.replica.confirmAt(newRoot); } /** * Retrieve the replica status of this message. * * @returns The {@link ReplicaMessageStatus} corresponding to the solidity * status of the message. */ async replicaStatus(): Promise<ReplicaMessageStatus> { return this.replica.messages(this.leaf); } /** * Checks whether the message has been delivered. * * @returns true if processed, else false. */ async delivered(): Promise<boolean> { const status = await this.replicaStatus(); return status === ReplicaMessageStatus.Processed; } /** * Returns a promise that resolves when the message has been delivered. * * WARNING: May never resolve. Oftern takes hours to resolve. * * @param opts Polling options. */ async wait(opts?: { pollTime?: number }): Promise<void> { const interval = opts?.pollTime ?? 5000; // sad spider face for (;;) { if (await this.delivered()) { return; } await delay(interval); } } /** * The domain from which the message was sent */ get from(): number { return this.message.from; } /** * The domain from which the message was sent. Alias for `from` */ get origin(): number { return this.from; } /** * The identifier for the sender of this message */ get sender(): string { return this.message.sender; } /** * The domain nonce for this message */ get nonce(): number { return this.message.nonce; } /** * The destination domain for this message */ get destination(): number { return this.message.destination; } /** * The identifer for the recipient for this message */ get recipient(): string { return this.message.recipient; } /** * The message body */ get body(): string { return this.message.body; } /** * The keccak256 hash of the message body */ get bodyHash(): string { return keccak256(this.body); } /** * The hash of the transaction that dispatched this message */ get transactionHash(): string { return this.dispatch.event.transactionHash; } /** * The messageHash committed to the tree in the Home contract. */ get leaf(): string { return this.dispatch.event.args.messageHash; } /** * The index of the leaf in the contract. */ get leafIndex(): BigNumber { return this.dispatch.event.args.leafIndex; } /** * The destination and nonceof this message. */ get destinationAndNonce(): BigNumber { return this.dispatch.event.args.destinationAndNonce; } /** * The committed root when this message was dispatched. */ get committedRoot(): string { return this.dispatch.event.args.committedRoot; } }
the_stack
'use strict'; import { expect } from 'chai'; import * as ComponentFactory from '../../../../src/lib/device/componentFactory'; const PREFIX = 'PREFIX/'; describe('./lib/device/componentFactory.ts', () => { describe('buildButton()', () => { it('should set default label', () => { const param = { name: 'buttonname' }; const button = ComponentFactory.buildButton(PREFIX, param); expect(button).to.deep.equal({ type: 'button', name: 'buttonname', label: 'buttonname', path: PREFIX + 'buttonname', }); }); it('should use optional label', () => { const param = { name: 'buttonname', label: 'a button' }; const button = ComponentFactory.buildButton(PREFIX, param); expect(button).to.deep.equal({ type: 'button', name: 'buttonname', label: 'a%20button', path: PREFIX + 'buttonname', }); }); it('should fail with missing pathprefix', () => { expect(() => { // @ts-ignore ComponentFactory.buildButton(); }).to.throw(/INVALID_PATHPREFIX/); }); it('should fail with missing build parameter', () => { expect(() => { // @ts-ignore ComponentFactory.buildButton('foo'); }).to.throw(/INVALID_BUILD_PARAMETER/); }); it('should fail with empty build parameter', () => { expect(() => { // @ts-ignore ComponentFactory.buildButton('foo', {}); }).to.throw(/INVALID_BUILD_PARAMETER/); }); }); describe('buildRangeSlider', () => { it('should build a slider', () => { const param = { name: 'slidername' }; const slider = ComponentFactory.buildRangeSlider(PREFIX, param); expect(slider).to.deep.equal({ type: 'slider', name: 'slidername', label: 'slidername', path: PREFIX + 'slidername', slider: { type: 'range', sensor: 'SLIDERNAME_SENSOR', range: [0, 100], unit: '%', }, }); }); it('should properly encode special characters in name', () => { const param = { name: 'slidername ✘✘ //\\<script>' }; const slider = ComponentFactory.buildRangeSlider(PREFIX, param); expect(slider).to.deep.equal({ type: 'slider', name: 'slidername%20%E2%9C%98%E2%9C%98%20%2F%2F%5C%3Cscript%3E', label: 'slidername%20%E2%9C%98%E2%9C%98%20%2F%2F%5C%3Cscript%3E', path: PREFIX + 'slidername%20%E2%9C%98%E2%9C%98%20%2F%2F%5C%3Cscript%3E', slider: { type: 'range', sensor: 'SLIDERNAME%20%E2%9C%98%E2%9C%98%20%2F%2F%5C%3CSCRIPT%3E_SENSOR', range: [0, 100], unit: '%', }, }); }); it('should respect optional parameters', () => { const param = { name: 'slidername', label: 'sliderfoo', range: [0, 10], unit: 'BAR', }; const slider = ComponentFactory.buildRangeSlider(PREFIX, param); expect(slider).to.deep.equal({ type: 'slider', name: 'slidername', label: 'sliderfoo', path: PREFIX + 'slidername', slider: { type: 'range', sensor: 'SLIDERNAME_SENSOR', range: [0, 10], unit: 'BAR', }, }); }); it('should fail with invalid range type', () => { expect(() => { const param = { name: 'slidername', label: 'sliderfoo', range: 'lala', unit: 'BAR', }; // @ts-ignore ComponentFactory.buildRangeSlider(PREFIX, param); }).to.throw(/INVALID_SLIDER_RANGE/); }); it('should fail with invalid range values', () => { expect(() => { const param = { name: 'slidername', label: 'sliderfoo', range: ['lala', 'land'], unit: 'BAR', }; // @ts-ignore ComponentFactory.buildRangeSlider(PREFIX, param); }).to.throw(/INVALID_SLIDER_RANGE/); }); it('should fail with missing pathprefix', () => { expect(() => { // @ts-ignore ComponentFactory.buildRangeSlider(); }).to.throw(/INVALID_PATHPREFIX/); }); }); describe('buildSwitch()', () => { it('should fail with missing pathprefix', () => { expect(() => { // @ts-ignore ComponentFactory.buildSwitch(); }).to.throw(/INVALID_PATHPREFIX/); }); }); describe('buildSensor()', () => { context('type range (default fallback)', () => { // TODO fix legacy build sensor functions without _SENSOR and lower case. it('should build a minimal range sensor if type not specified', () => { const param = { name: 'aRangeSensor', }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor).to.deep.equal({ type: 'sensor', name: 'aRangeSensor', label: 'aRangeSensor', path: PREFIX + 'aRangeSensor', sensor: { range: [0, 100], type: 'range', unit: '%', }, }); }); // TODO fix legacy build sensor functions without _SENSOR and lower case. it('should build a advanced range sensor', () => { const param = { name: 'aRangeSensor', label: 'foo', unit: '"', range: [5, 12], }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor).to.deep.equal({ type: 'sensor', name: 'aRangeSensor', label: 'foo', path: PREFIX + 'aRangeSensor', sensor: { range: [5, 12], type: 'range', unit: '%22', }, }); }); it('should use component label if set', () => { const param = { type: 'range', name: 'range', label: 'Range' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Range'); }); it('should use component sensorlabel if set', () => { const param = { type: 'range', name: 'range', sensorlabel: 'Range sensor', label: 'Range', }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Range%20sensor'); }); }); context('type range', () => { it('should slider sensor, using default fallbacks', () => { const param = { type: 'range', name: 'slider' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor).to.deep.equal({ type: 'sensor', name: 'SLIDER_SENSOR', label: 'slider', path: PREFIX + 'SLIDER_SENSOR', sensor: { type: 'range', range: [0, 100], unit: '%', }, }); }); it('should use component unit if set', () => { const param = { type: 'range', name: 'slider', unit: 'mm' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); // @ts-ignore expect(sensor.sensor.unit).to.equal('mm'); }); it('should use component range if set', () => { const param = { type: 'range', name: 'slider', range: [180, 360] }; const sensor = ComponentFactory.buildSensor(PREFIX, param); // @ts-ignore expect(sensor.sensor.range).to.deep.equal([180, 360]); }); it('should fail for invalid range type', () => { const param = { type: 'range', name: 'slider', range: '1 to 10' }; expect(() => { // @ts-ignore ComponentFactory.buildSensor(PREFIX, param); }).to.throw(/INVALID_SLIDER_RANGE/); }); it('should fail for invalid range values', () => { const param = { type: 'range', name: 'slider', range: ['a', 'z'] }; expect(() => { // @ts-ignore ComponentFactory.buildSensor(PREFIX, param); }).to.throw(/INVALID_SLIDER_RANGE/); }); it('should use component label if set', () => { const param = { type: 'range', name: 'slider', label: 'Slider' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Slider'); }); it('should prioritize sensorlabel if set', () => { const param = { type: 'range', name: 'slider', sensorlabel: 'Slider sensor', label: 'Slider', }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Slider%20sensor'); }); }); context('type power', () => { // TODO fix legacy build sensor functions without _SENSOR and lower case. it('should build a power sensor', () => { const param = { name: 'aPowerSensor', type: 'power' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor).to.deep.equal({ type: 'sensor', name: 'aPowerSensor', label: 'aPowerSensor', path: PREFIX + 'aPowerSensor', sensor: { type: 'power', }, }); }); it('should use component label if set', () => { const param = { type: 'power', name: 'power', label: 'Power' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Power'); }); it('should use sensorlabel if set', () => { const param = { type: 'power', name: 'power', sensorlabel: 'Power sensor', label: 'Power', }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Power%20sensor'); }); }); context('type binary', () => { it('should build sensor, using name as label fallback', () => { const param = { type: 'binary', name: 'binary' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor).to.deep.equal({ type: 'sensor', name: 'BINARY_SENSOR', label: 'binary', path: PREFIX + 'BINARY_SENSOR', sensor: { type: 'binary', }, }); }); it('should use component label if set', () => { const param = { type: 'binary', name: 'binary', label: 'Binary' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Binary'); }); it('should prioritize sensorlabel if set', () => { const param = { type: 'binary', name: 'binary', sensorlabel: 'Binary sensor', label: 'Binary', }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Binary%20sensor'); }); }); context('type custom', () => { it('should build custom sensor, using name as label fallback', () => { const param = { type: 'custom', name: 'custom' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor).to.deep.equal({ type: 'sensor', name: 'CUSTOM_SENSOR', label: 'custom', path: PREFIX + 'CUSTOM_SENSOR', sensor: { type: 'custom', }, }); }); it('should use component label if set', () => { const param = { type: 'custom', name: 'custom', label: 'Custom' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Custom'); }); it('should prioritize sensorlabel if set', () => { const param = { type: 'custom', name: 'custom', sensorlabel: 'Custom sensor', label: 'Custom', }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Custom%20sensor'); }); }); context('type string', () => { it('should build string sensor, using name as label fallback', () => { const param = { type: 'string', name: 'string' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor).to.deep.equal({ type: 'sensor', name: 'STRING_SENSOR', label: 'string', path: PREFIX + 'STRING_SENSOR', sensor: { type: 'string', }, }); }); it('should use component label if set', () => { const param = { type: 'string', name: 'string', label: 'String' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('String'); }); it('should prioritize sensorlabel if set', () => { const param = { type: 'string', name: 'string', sensorlabel: 'String sensor', label: 'String', }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('String%20sensor'); }); }); context('type array', () => { it('should switch sensor, using name as label fallback', () => { const param = { type: 'array', name: 'array' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor).to.deep.equal({ type: 'sensor', name: 'ARRAY_SENSOR', label: 'array', path: PREFIX + 'ARRAY_SENSOR', sensor: { type: 'array', }, }); }); it('should use component label if set', () => { const param = { type: 'array', name: 'array', label: 'Array' }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Array'); }); it('should prioritize sensorlabel if set', () => { const param = { type: 'array', name: 'array', sensorlabel: 'Array sensor', label: 'Array', }; const sensor = ComponentFactory.buildSensor(PREFIX, param); expect(sensor.label).to.equal('Array%20sensor'); }); }); }); describe('buildTextLabel()', () => { it('should set default label value but not visible', () => { const param = { name: 'textlabel' }; const textlabel = ComponentFactory.buildTextLabel(PREFIX, param); expect(textlabel).to.deep.equal({ type: 'textlabel', name: 'textlabel', label: 'textlabel', isLabelVisible: undefined, path: PREFIX + 'textlabel', sensor: 'TEXTLABEL_SENSOR', }); }); it('should respect isLabelVisible parameter when false', () => { const param = { name: 'textlabel', isLabelVisible: false }; const textlabel = ComponentFactory.buildTextLabel(PREFIX, param); expect(textlabel).to.deep.equal({ type: 'textlabel', name: 'textlabel', label: 'textlabel', isLabelVisible: false, path: PREFIX + 'textlabel', sensor: 'TEXTLABEL_SENSOR', }); }); it('should allow enabling the label', () => { const param = { name: 'textlabel', isLabelVisible: true }; const textlabel = ComponentFactory.buildTextLabel(PREFIX, param); expect(textlabel).to.deep.equal({ type: 'textlabel', name: 'textlabel', label: 'textlabel', isLabelVisible: true, path: PREFIX + 'textlabel', sensor: 'TEXTLABEL_SENSOR', }); }); it('should fail with empty controller', () => { expect(() => { // @ts-ignore ComponentFactory.buildTextLabel('foo', {}); }).to.throw(/INVALID_BUILD_PARAMETER/); }); }); describe('buildImageUrl', () => { it('should fail with invalid size', () => { const param = { name: 'imageurl', size: 'invalid' }; // @ts-ignore const fn = () => ComponentFactory.buildImageUrl(PREFIX, param); expect(fn).to.throw(/INVALID_IMAGEURL_SIZE/); }); it('should defaults to large when using no valid size definition', () => { const param = { name: 'imageurl', szie: 'large' }; // @ts-ignore const image = ComponentFactory.buildImageUrl(PREFIX, param); expect(image.size).to.equal('large'); }); it('should build an imageurl, without label', () => { const param = { name: 'imageurl' }; // @ts-ignore const image = ComponentFactory.buildImageUrl(PREFIX, param); expect(image).to.deep.equal({ type: 'imageurl', name: 'imageurl', label: 'imageurl', size: 'large', path: PREFIX + 'imageurl', imageUri: null, sensor: 'IMAGEURL_SENSOR', }); }); it('should fail with empty controller', () => { expect(() => { // @ts-ignore ComponentFactory.buildImageUrl('foo', {}); }).to.throw(/INVALID_BUILD_PARAMETER/); }); }); describe('buildDirectory()', () => { it('should build a directory, using parameters', () => { const param = { name: 'directoryname', label: 'somelabel' }; const result = ComponentFactory.buildDirectory(PREFIX, param); expect(result).to.deep.equal({ identifier: undefined, role: undefined, name: 'directoryname', label: 'somelabel', path: PREFIX + 'directoryname', type: 'directory', }); }); it('should build a directory, using adapterName parameter', () => { const param = { name: 'directoryname', label: 'somelabel', adapterName: 'device', }; const result = ComponentFactory.buildDirectory(PREFIX, param); expect(result).to.deep.equal({ identifier: undefined, role: undefined, name: 'directoryname', label: 'somelabel', path: PREFIX + 'directoryname', type: 'directory', }); }); it('should fail with missing build parameter', () => { expect(() => { // @ts-ignore ComponentFactory.buildDirectory('foo'); }).to.throw(/INVALID_BUILD_PARAMETER/); }); it('should fail with empty build parameter', () => { expect(() => { // @ts-ignore ComponentFactory.buildDirectory('foo', {}); }).to.throw(/INVALID_BUILD_PARAMETER/); }); }); describe('buildDiscovery()', () => { it('should fail to build a discovery, missing build parameter', () => { expect(() => { // @ts-ignore ComponentFactory.buildDiscovery(); }).to.throw(/INVALID_PATHPREFIX/); }); it('should build a discovery component', () => { const result = ComponentFactory.buildDiscovery(PREFIX); expect(result).to.deep.equal({ name: 'discover', path: PREFIX + 'discover', type: 'discover', }); }); }); describe('buildRegister', () => { it('should fail to build a register, missing build parameter', () => { expect(() => { // @ts-ignore ComponentFactory.buildRegister(); }).to.throw(/INVALID_PATHPREFIX/); }); it('should build a register component', () => { const result = ComponentFactory.buildRegister(PREFIX); expect(result).to.deep.equal({ name: 'register', path: PREFIX + 'register', type: 'register', }); }); }); describe('buildFavoritesHandler()', () => { it('should fail to build a discovery, missing build parameter', () => { // @ts-ignore expect(() => ComponentFactory.buildFavoritesHandler()) .to.throw(/INVALID_PATHPREFIX/); }); it('should build a discovery component', () => { const result = ComponentFactory.buildFavoritesHandler(PREFIX); expect(result).to.deep.equal({ name: 'favoritehandler', path: PREFIX + 'favoritehandler', type: 'favoritehandler', }); }); }); });
the_stack
import { UserAccount, UserAccountOptions } from '../models/user-account'; import fetch, { Response } from 'node-fetch'; import { convertToMediaPost, convertToMediaPosts, MediaPost, MediaPostOptions, } from '../models/post'; import { Utils } from '../modules/utils/utils'; import { IResult } from '../models/http-result'; const EndPoints = { baseUrl: 'https://www.instagram.com/', feed: () => `${EndPoints.baseUrl}?__a=1`, login: () => `${EndPoints.baseUrl}accounts/login/ajax/`, logout: () => `${EndPoints.baseUrl}accounts/logout`, exploreTag: (tag: string) => `${EndPoints.baseUrl}explore/tags/${tag}/?__a=1`, exploreLocation: (location: string) => `${EndPoints.baseUrl}explore/locations/${location}/?__a=1`, like: (id: string, isDislike: boolean = false) => `${EndPoints.baseUrl}web/likes/${id}/${isDislike ? 'unlike' : 'like'}/`, comment: (id: string) => `${EndPoints.baseUrl}web/comments/${id}/add/`, follow: (userId: string, isUnfollow: boolean = false) => `${EndPoints.baseUrl}web/friendships/${userId}/${ isUnfollow === true ? 'unfollow' : 'follow' }/`, mediaDetails: (id: string) => `${EndPoints.baseUrl}p/${id}/?__a=1`, userDetails: (username: string) => `${EndPoints.baseUrl}${username}/?__a=1`, userDetailsById: (userId: string) => `https://i.instagram.com/api/v1/users/${userId}/info/`, getUsersThatLikedMedia: (shortcode: string, first: number) => `${ EndPoints.baseUrl }graphql/query/?query_hash=e0f59e4a1c8d78d0161873bc2ee7ec44&variables=%7B%22shortcode%22%3A%22${shortcode}%22%2C%22include_reel%22%3Afalse%2C%22first%22%3A${first}%7D`, }; /*const Matchers = { sharedData: /\<script type=\"text\/javascript\">window\._sharedData \=(.*)\;<\//, };*/ export class HttpService { // region Internal Variables /** * Random user-agent to be used, consistent from the beginning * */ private userAgent: string = Utils.getFakeUserAgent(); /** * csrfToken for instagram * */ private csrfToken: string = undefined; /** * when logged in, sessionId is being saved here * */ private sessionId: string = undefined; /** * Hidden header that needs to be set * */ private rollout_hash: string; /** * Cookies set over time, appended on the requests * */ private essentialCookies = { sessionid: undefined, ds_user_id: undefined, csrftoken: undefined, shbid: undefined, rur: undefined, mid: undefined, shbts: undefined, mcd: undefined, ig_cb: 1, //urlgen : undefined //this needs to be filled in according to my RE }; private language: string = 'en-US;q=0.9,en;q=0.8,es;q=0.7'; private baseHeader = { 'accept-langauge': this.language, origin: 'https://www.instagram.com', referer: 'https://www.instagram.com/', 'upgrade-insecure-requests': '1', 'user-agent': this.userAgent, }; // endregion /** * Which languages should be set on the header * */ constructor( public options?: { followerOptions: UserAccountOptions; postOptions: MediaPostOptions; }, ) { if (!options) { this.options = { followerOptions: { unwantedUsernames: [], followFakeUsers: false, followSelebgramUsers: false, followPassiveUsers: false, }, postOptions: { maxLikesToLikeMedia: 600, minLikesToLikeMedia: 5, }, }; } } /** * Get csrf token * @return {Object} Promise<IResult<string>> */ public getCsrfToken(): Promise<IResult<string>> { return new Promise<IResult<string>>((resolve, reject) => { fetch('https://www.instagram.com', { method: 'get', headers: this.combineWithBaseHeader({ accept: 'text/html,application/xhtml+xml,application/xml;q0.9,image/webp,image/apng,*.*;q=0.8', 'accept-encoding': 'gzip, deflate, br', cookie: this.generateCookie(true), }), }) .then(response => { this.updateEssentialValues(response.headers.raw()['set-cookie']); this.csrfToken = this.essentialCookies.csrftoken; response .text() .then(html => { this.updateEssentialValues(html, true); this.csrfToken = this.essentialCookies.csrftoken; return resolve(Utils.getResult(response, this.csrfToken)); }) .catch(() => { return reject('Could not get CSRF-Token of Instagram'); }); }) .catch(() => { return reject('Could not get CSRF-Token of Instagram'); }); }); } private getFormDataPairs(data: object, pairs: string[] = []): string[] { // Turn the data object into an array of URL-encoded key/value pairs. for (let name in data) { pairs.push( encodeURIComponent(name) + '=' + encodeURIComponent(data[name]), ); } return pairs; } private getFormData(data: object) { const pairs = this.getFormDataPairs(data); // Combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behaviour of browser form submissions. return pairs.join('&').replace(/%20/g, '+'); } /** * Session id by username and password * @return {any} Promise * @param credentials */ public login(credentials: { username: string; password: string; }): Promise<IResult<string>> { /*let yes = true;*/ const formdata = this.getFormData({ username: credentials.username, password: credentials.password, }); let options = { method: 'POST', body: formdata, headers: this.combineWithBaseHeader({ accept: '*/*', 'accept-encoding': 'gzip, deflate, br', 'content-length': formdata.length, 'content-type': 'application/x-www-form-urlencoded', cookie: 'ig_cb=' + this.essentialCookies.ig_cb, 'x-csrftoken': this.csrfToken, 'x-instagram-ajax': this.rollout_hash, 'x-requested-with': 'XMLHttpRequest', referer: 'https://www.instagram.com/accounts/login/?source=auth_switcher', }), }; return new Promise<IResult<string>>((resolve, reject) => { fetch(EndPoints.login(), options) .then(response => { return response .json() .then(json => { if ( json && json['authenticated'] === true && json['user'] === true ) { this.updateEssentialValues( response.headers.raw()['set-cookie'], ); this.sessionId = this.essentialCookies.sessionid; return resolve( Utils.getResult(response, this.essentialCookies.sessionid), ); } else { return reject( 'Authentication failed... Is your username and your password right?', ); } }) .catch(() => { //json error, not right response, login failed return reject( 'Could not login with your username and password... Try again.', ); }); /*this.updateEssentialValues(response.headers.raw()['set-cookie']); this.sessionId = this.essentialCookies.sessionid; return resolve( Utils.getResult(response, this.essentialCookies.sessionid), );*/ }) .catch(() => { return reject( 'Could not login with your username and password... Try again.', ); }); }); } /** * logs out the current user * @return {Object} Promise<IResult<boolean>> */ public logout(): Promise<IResult<boolean>> { if (!this.csrfToken || this.csrfToken.length < 2) { return Promise.reject('cannot logout if not logged in'); } const formdata = this.getFormData({ csrfmiddlewaretoken: this.csrfToken, }); let options = { method: 'POST', body: formdata, headers: this.combineWithBaseHeader({ accept: '*/*', 'accept-encoding': 'gzip, deflate, br', 'content-length': formdata.length, 'content-type': 'application/x-www-form-urlencoded', cookie: 'ig_cb=' + this.essentialCookies.ig_cb, 'x-csrftoken': this.csrfToken, 'x-instagram-ajax': this.rollout_hash, 'x-requested-with': 'XMLHttpRequest', }), }; return new Promise((resolve, reject) => { fetch(EndPoints.logout(), options) .then(t => { this.updateEssentialValues(t.headers.raw()['set-cookie']); this.sessionId = undefined; this.csrfToken = undefined; return resolve(Utils.getResult(t, t.ok)); }) .catch(() => { return reject('Instagram logout failed'); }); }); } /** * Follow/unfollow user by id * @description always resolves the promise, never rejects * @param {string} userId * @param {boolean} isUnfollow, if true user will be unfollowed * @return {object} Promise<IResult<boolean>> */ public follow( userId: string, isUnfollow: boolean = false, ): Promise<IResult<boolean>> { return new Promise<IResult<boolean>>(resolve => { fetch(EndPoints.follow(userId, isUnfollow), { method: 'post', headers: this.getHeaders(), //headers }) .then(r => { return resolve({ status: r.status, success: r.ok, }); }) .catch(() => { return resolve({ status: 500, success: false, }); }); }); } /** * Gets an amount of posts based on the specific hashtag * @description always resolves the promise, never rejects * @param {string} hashtag * @returns {Promise<IResult<MediaPost[]>>} */ public getMediaByHashtag(hashtag: string): Promise<IResult<MediaPost[]>> { return new Promise<IResult<MediaPost[]>>(resolve => { fetch(EndPoints.exploreTag(hashtag), { method: 'get', headers: this.getHeaders(), }) .then((response: Response) => { response .json() .then(json => { if (json == null) { return resolve(Utils.getResult(response, [])); } else { return resolve( Utils.getResult( response, convertToMediaPosts( Utils.getPostsOfHashtagGraphQL(json), this.options.postOptions, ), ), ); } }) .catch(() => { return resolve({ status: 500, success: false, data: [], }); }); }) .catch(() => { return resolve({ status: 500, success: false, data: [], }); }); }); } public getMediaPostPage(shortcode: string): Promise<IResult<MediaPost>> { if(typeof shortcode !== 'string' || shortcode.length < 1){ return Promise.resolve({ status: 500, success: false, data: null, }); } return new Promise<IResult<MediaPost>>(resolve => { fetch(EndPoints.mediaDetails(shortcode), { method: 'get', headers: this.getHeaders(), }) .then((response: Response) => { response .json() .then(json => { if (json == null) { return resolve(Utils.getResult(response, null)); } else { return resolve( Utils.getResult<MediaPost>( response, convertToMediaPost(Utils.getPostGraphQL(json)), ), ); } }) .catch(err => { console.error('JSON ERROR', err); return resolve({ status: 500, success: false, data: null, }); }); }) .catch(err => { console.error('RESPONSE ERROR', err); return resolve({ status: 500, success: false, data: null, }); }); }); } /*public getUsersByLikedMedia(shortcode: string, userCount: number = 24): Promise<IResult<UserAccount[]>>{ return new Promise<IResult<UserAccount[]>>((resolve)=>{ fetch(EndPoints.getUsersByLikedMedia(shortcode, userCount),{ method: 'get', headers: this.getHeaders(), }).then((response)=>{ }).catch(() =>{ return resolve({ status: 500, success:false, data: [] }) }) }); }*/ /** * gets details about an user by the username * @description always resolves the promise, never rejects * @param username, username of the user * @param options * @returns Promise<IResult<UserAccount>> * */ public getUserInfo(username: string): Promise<IResult<UserAccount>> { return new Promise<IResult<UserAccount>>(resolve => { fetch(EndPoints.userDetails(username), { method: 'get', headers: this.getHeaders(), }) .then(response => { /*return response .text() .then(text => { try { let userData = this.getSharedData(text)['entry_data'][ 'ProfilePage' ][0]['graphql']['user']; return resolve( Utils.getResult( response, UserAccount.getUserByProfileData(userData, options), ), ); } catch (e) { console.error('getUserInfo text error', e); return resolve({ status: 500, success: false, data: null, }); } }) .catch(err => { console.error('getUserInfo text error', err); return resolve({ status: 500, success: false, data: null, }); });*/ return response .json() .then(json => { if ( json == null || !json['graphql'] || !json['graphql']['user'] ) { return resolve({ status: response.status, success: false, data: null, }); } const userData = json['graphql']['user']; return resolve( Utils.getResult( response, UserAccount.getUserByProfileData( userData, this.options.followerOptions, ), ), ); }) .catch(err => { console.error('json error', err); return resolve({ status: 500, success: false, data: null, }); }); }) .catch(err => { console.error('request failed', err); return resolve({ status: 500, success: false, data: null, }); }); }); } /** * gets details about an user by the id * @description always resolves the promise, never rejects * @param {string} userId, id of the user * @param options * @returns Promise<IResult<UserAccount>> * */ public getUserInfoById(userId: string): Promise<IResult<UserAccount>> { return new Promise<IResult<UserAccount>>(resolve => { fetch(EndPoints.userDetailsById(userId), { method: 'get', headers: this.getHeaders(), }) .then(response => { return response .json() .then(json => { if (!json || !json['user']) { return null; } if (response.ok !== true) { return resolve(Utils.getResult(response, null)); } else { // get complete userinfo by profile Utils.quickSleep().then(() => { this.getUserInfo(json['user']['username']).then(result => { return resolve(result); }); }); } }) .catch(() => { return resolve({ status: 500, success: false, data: null, }); }); }) .catch(() => { return resolve({ status: 500, success: false, data: null, }); }); }); } /** * Attention: postId need transfer only as String (reason int have max value - 2147483647) * @description always resolves the promise, never rejects * @example postId - '1510335854710027921' * @param {string} postId * @param {boolean} isDislike, if its a request to unlike an post * @return {object} Promise<IResult<boolean>> */ public like( postId: string, isDislike: boolean = false, ): Promise<IResult<boolean>> { return new Promise<IResult<boolean>>(resolve => { fetch(EndPoints.like(postId, isDislike), { method: 'POST', headers: this.getHeaders(), follow: 0, }) .then(response => resolve(Utils.getResult(response, response.ok))) .catch(err => { console.error('like error,', err); return resolve({ status: 500, success: false, data: false, }); }); }); } // endregion // region Internal Functions /** * @return {Object} default headers */ private getHeaders(): any { return { referer: 'https://www.instagram.com/p/BT1ynUvhvaR/?taken-by=yatsenkolesh', origin: 'https://www.instagram.com', 'user-agent': this.userAgent, 'x-instagram-ajax': this.rollout_hash ? this.rollout_hash : '1', 'x-requested-with': 'XMLHttpRequest', 'x-csrftoken': this.csrfToken, cookie: ' sessionid=' + this.sessionId + '; csrftoken=' + this.csrfToken + ';', }; } private generateCookie(simple?: boolean): string { if (simple) return 'ig_cb=1'; let cookie = ''; let keys = Object.keys(this.essentialCookies); for (let i = 0; i < keys.length; i++) { let key = keys[i]; cookie += key + '=' + this.essentialCookies[key] + (i < keys.length - 1 ? '; ' : ''); } return cookie; } private combineWithBaseHeader(data: object): any { return Object.assign(this.baseHeader, data); } private updateEssentialValues(src, isHTML: boolean = false): void { //assumes that essential values will be extracted from // a cookie unless specified by the isHTML bool if (!isHTML) { let keys = Object.keys(this.essentialCookies); for (let i = 0; i < keys.length; i++) { let key = keys[i]; if (!this.essentialCookies[key]) for (let cookie in src) if ( src[cookie].includes(key) && !src[cookie].includes(key + '=""') ) { this.essentialCookies[key] = src[cookie] .split(';')[0] .replace(key + '=', ''); break; } } } else { let subStr = src; let startStr = '<script type="text/javascript">window._sharedData = '; let start = subStr.indexOf(startStr) + startStr.length; subStr = subStr.substr(start, subStr.length); subStr = subStr.substr(0, subStr.indexOf('</script>') - 1); let json = JSON.parse(subStr); this.essentialCookies.csrftoken = json.config.csrf_token; this.rollout_hash = json.rollout_hash; } } // endregion // region HelperFunctions /*private getSharedData(htmlText: string): object { try { if (htmlText) { return JSON.parse(Matchers.sharedData.exec(htmlText)[1]); } else { return null; } } catch (e) { return null; } }*/ /*private getSharedData(htmlText: string): object { try { if (htmlText) { return JSON.parse(htmlText.match(Matchers.sharedData)[1]); } else { return null; } } catch (e) { return null; } } private getPostsOfHashtagPage(page: object) { if (page && page['entry_data']) { return page['entry_data']['TagPage'][0]['graphql']['hashtag'][ 'edge_hashtag_to_media' ]['edges']; } else { return []; } }*/ // endregion }
the_stack
import { Bounds, Epsg, Stac, StacCollection, StacLink, StacProvider, TileMatrixSet, TileMatrixSets, } from '@basemaps/geo'; import { extractYearRangeFromName, FileConfig, FileConfigPath, Projection, fsa, titleizeImageryName, CompositeError, } from '@basemaps/shared'; import { MultiPolygon, toFeatureCollection, toFeatureMultiPolygon } from '@linzjs/geojson'; import { CliInfo } from '../cli/base.cli.js'; import { GdalCogBuilderDefaults, GdalCogBuilderResampling } from '../gdal/gdal.config.js'; import { CogStac, CogStacItem, CogStacItemExtensions, CogStacKeywords } from './stac.js'; import { CogBuilderMetadata, CogJob, CogJobJson, CogOutputProperties, CogSourceProperties, FeatureCollectionWithCrs, } from './types.js'; export const MaxConcurrencyDefault = 50; export interface JobCreationContext { /** Source config */ sourceLocation: FileConfig | FileConfigPath; /** Output config */ outputLocation: FileConfig; /** Should the imagery be cut to a cutline */ cutline?: { href: string; blend: number; }; tileMatrix: TileMatrixSet; override?: { /** Override job id */ id?: string; /** * Image quality * @default GdalCogBuilderDefaults.quality */ quality?: number; /** * Number of threads to use for fetches * @default MaxConcurrencyDefault */ concurrency?: number; /** * Override the source projection */ projection?: Epsg; /** * Resampling method * @Default GdalCogBuilderDefaults.resampling */ resampling?: GdalCogBuilderResampling; }; /** * Should this job be submitted to batch now? * @default false */ batch: boolean; /** Should this job ignore source coverage and just produce one big COG for EPSG extent */ oneCogCovering: boolean; } export interface CogJobCreateParams { /** unique id for imagery set */ id: string; /** name of imagery set */ imageryName: string; /** information about the source */ metadata: CogBuilderMetadata; /** information about the output */ ctx: JobCreationContext; /** the polygon to use to clip the source imagery */ cutlinePoly: MultiPolygon; /** do we need an alpha band added */ addAlpha: boolean; } /** * Information needed to create cogs */ export class CogStacJob implements CogJob { json: CogJobJson; private cacheTargetZoom?: { gsd: number; zoom: number; }; /** * Load the job.json * @param jobpath where to load the job.json from */ static async load(jobpath: string): Promise<CogStacJob> { return new CogStacJob(await fsa.readJson<CogJobJson>(jobpath)); } /** * Create job.json, collection.json, source.geojson, covering.geojson, cutlint.geojson.gz and * stac descriptions of the target COGs */ static async create({ id, imageryName, metadata, ctx, cutlinePoly, addAlpha, }: CogJobCreateParams): Promise<CogStacJob> { let description: string | undefined; const providers: StacProvider[] = []; const links: StacLink[] = [ { href: fsa.join(ctx.outputLocation.path, 'collection.json'), type: 'application/json', rel: 'self', }, { href: 'job.json', type: 'application/json', rel: 'linz.basemaps.job', }, ]; let sourceStac = {} as StacCollection; const interval: [string, string][] = []; try { const sourceCollectionPath = fsa.join(ctx.sourceLocation.path, 'collection.json'); sourceStac = await fsa.readJson<StacCollection>(sourceCollectionPath); description = sourceStac.description; interval.push(...(sourceStac.extent?.temporal?.interval ?? [])); links.push({ href: sourceCollectionPath, rel: 'sourceImagery', type: 'application/json' }); if (sourceStac.providers != null) { for (const p of sourceStac.providers) { if (p.roles.indexOf('host') === -1) { if (p.url === 'unknown') { // LINZ LDS has put unknown in some urls p.url = undefined; } providers.push(p); } } } } catch (err) { if (!CompositeError.isCompositeError(err) || err.code !== 404) { throw err; } } const keywords = sourceStac.keywords ?? CogStacKeywords.slice(); const license = sourceStac.license ?? Stac.License; const title = sourceStac.title ?? titleizeImageryName(imageryName); if (description == null) { description = 'No description'; } const job = new CogStacJob({ id, name: imageryName, title, description, source: { gsd: metadata.pixelScale, epsg: metadata.projection, files: metadata.bounds, location: ctx.sourceLocation, }, output: { gsd: ctx.tileMatrix.pixelScale(metadata.resZoom), tileMatrix: ctx.tileMatrix.identifier, epsg: ctx.tileMatrix.projection.code, files: metadata.files, location: ctx.outputLocation, resampling: ctx.override?.resampling ?? GdalCogBuilderDefaults.resampling, quality: ctx.override?.quality ?? GdalCogBuilderDefaults.quality, cutline: ctx.cutline, addAlpha, nodata: metadata.nodata, bounds: metadata.targetBounds, oneCogCovering: ctx.oneCogCovering, }, }); const nowStr = new Date().toISOString(); const sourceProj = Projection.get(job.source.epsg); const bbox = [ sourceProj.boundsToWgs84BoundingBox( metadata.bounds.map((a) => Bounds.fromJson(a)).reduce((sum, a) => sum.union(a)), ), ]; if (interval.length === 0) { const years = extractYearRangeFromName(imageryName); if (years[0] === -1) { throw new Error('Missing date in imagery name: ' + imageryName); } interval.push(years.map((y) => `${y}-01-01T00:00:00Z`) as [string, string]); } if (ctx.cutline) { links.push({ href: 'cutline.geojson.gz', type: 'application/geo+json+gzip', rel: 'linz.basemaps.cutline' }); } links.push({ href: 'covering.geojson', type: 'application/geo+json', rel: 'linz.basemaps.covering' }); links.push({ href: 'source.geojson', type: 'application/geo+json', rel: 'linz.basemaps.source' }); const temporal = { interval }; const jobFile = job.getJobPath(`job.json`); const stac: CogStac = { id, title, description, stac_version: Stac.Version, stac_extensions: [Stac.BaseMapsExtension], extent: { spatial: { bbox }, temporal, }, license, keywords, providers, summaries: { gsd: [metadata.pixelScale], 'proj:epsg': [ctx.tileMatrix.projection.code], 'linz:output': [ { resampling: ctx.override?.resampling ?? GdalCogBuilderDefaults.resampling, quality: ctx.override?.quality ?? GdalCogBuilderDefaults.quality, cutlineBlend: ctx.cutline?.blend, addAlpha, nodata: metadata.nodata, }, ], 'linz:generated': [ { ...CliInfo, datetime: nowStr, }, ], }, links, }; await fsa.writeJson(jobFile, job.json); const covering = Projection.get(job.tileMatrix).toGeoJson(metadata.files); const roles = ['data']; const collectionLink = { href: 'collection.json', rel: 'collection' }; for (const f of covering.features) { const { name } = f.properties as { name: string }; const href = name + '.json'; links.push({ href, type: 'application/geo+json', rel: 'item' }); const item: CogStacItem = { ...f, id: job.id + '/' + name, collection: job.id, stac_version: Stac.Version, stac_extensions: CogStacItemExtensions, properties: { ...f.properties, datetime: nowStr, gsd: job.output.gsd, 'proj:epsg': job.tileMatrix.projection.code, }, links: [{ href: job.getJobPath(href), rel: 'self' }, collectionLink], assets: { cog: { href: name + '.tiff', type: 'image/tiff; application=geotiff; profile=cloud-optimized', roles, }, }, }; await fsa.writeJson(job.getJobPath(href), item); } if (ctx.cutline != null) { const geoJsonCutlineOutput = job.getJobPath(`cutline.geojson.gz`); await fsa.writeJson(geoJsonCutlineOutput, this.toGeoJson(cutlinePoly, ctx.tileMatrix.projection)); } const geoJsonSourceOutput = job.getJobPath(`source.geojson`); await fsa.writeJson(geoJsonSourceOutput, Projection.get(job.source.epsg).toGeoJson(metadata.bounds)); const geoJsonCoveringOutput = job.getJobPath(`covering.geojson`); await fsa.writeJson(geoJsonCoveringOutput, covering); await fsa.writeJson(job.getJobPath(`collection.json`), stac); return job; } /** * build a FeatureCollection from MultiPolygon */ static toGeoJson(poly: MultiPolygon, epsg: Epsg): FeatureCollectionWithCrs { const feature = toFeatureCollection([toFeatureMultiPolygon(poly)]) as FeatureCollectionWithCrs; feature.crs = { type: 'name', properties: { name: epsg.toUrn() }, }; return feature; } constructor(json: CogJobJson) { this.json = json; } get id(): string { return this.json.id; } get name(): string { return this.json.name; } get title(): string { return this.json.title; } get description(): string | undefined { return this.json.description; } get source(): CogSourceProperties { return this.json.source; } get output(): CogOutputProperties { return this.json.output; } get tileMatrix(): TileMatrixSet { if (this.json.output.tileMatrix) { const tileMatrix = TileMatrixSets.find(this.json.output.tileMatrix); if (tileMatrix == null) throw new Error(`Failed to find TileMatrixSet "${this.json.output.tileMatrix}"`); return tileMatrix; } return TileMatrixSets.get(this.json.output.epsg); } get targetZoom(): number { const { gsd } = this.source; if (this.cacheTargetZoom?.gsd !== gsd) { this.cacheTargetZoom = { gsd, zoom: Projection.getTiffResZoom(this.tileMatrix, gsd) }; } return this.cacheTargetZoom.zoom; } /** * Get a nicely formatted folder path based on the job * * @param key optional file key inside of the job folder */ getJobPath(key?: string): string { const parts = [this.tileMatrix.projection.code, this.name, this.id]; if (key != null) { parts.push(key); } return fsa.join(this.output.location.path, parts.join('/')); } }
the_stack
import * as faker from 'faker/locale/en' // Ported from the original Postman implementation for dynamic-variables // https://github.com/postmanlabs/postman-collection/blob/develop/lib/superstring/dynamic-variables.js export class PostmanDynamicVarGenerator { dynamicGenerators: any constructor() { // locale list generated from: https://github.com/chromium/chromium/blob/master/ui/base/l10n/l10n_util.cc const LOCALES = [ 'af', 'am', 'an', 'ar', 'ast', 'az', 'be', 'bg', 'bh', 'bn', 'br', 'bs', 'ca', 'ceb', 'ckb', 'co', 'cs', 'cy', 'da', 'de', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fil', 'fo', 'fr', 'fy', 'ga', 'gd', 'gl', 'gn', 'gu', 'ha', 'haw', 'he', 'hi', 'hmn', 'hr', 'ht', 'hu', 'hy', 'ia', 'id', 'ig', 'is', 'it', 'ja', 'jv', 'ka', 'kk', 'km', 'kn', 'ko', 'ku', 'ky', 'la', 'lb', 'ln', 'lo', 'lt', 'lv', 'mg', 'mi', 'mk', 'ml', 'mn', 'mo', 'mr', 'ms', 'mt', 'my', 'nb', 'ne', 'nl', 'nn', 'no', 'ny', 'oc', 'om', 'or', 'pa', 'pl', 'ps', 'pt', 'qu', 'rm', 'ro', 'ru', 'sd', 'sh', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sq', 'sr', 'st', 'su', 'sv', 'sw', 'ta', 'te', 'tg', 'th', 'ti', 'tk', 'to', 'tr', 'tt', 'tw', 'ug', 'uk', 'ur', 'uz', 'vi', 'wa', 'xh', 'yi', 'yo', 'zh', 'zu' ] // paths for directories const DIRECTORY_PATHS = [ '/Applications', '/bin', '/boot', '/boot/defaults', '/dev', '/etc', '/etc/defaults', '/etc/mail', '/etc/namedb', '/etc/periodic', '/etc/ppp', '/home', '/home/user', '/home/user/dir', '/lib', '/Library', '/lost+found', '/media', '/mnt', '/net', '/Network', '/opt', '/opt/bin', '/opt/include', '/opt/lib', '/opt/sbin', '/opt/share', '/private', '/private/tmp', '/private/var', '/proc', '/rescue', '/root', '/sbin', '/selinux', '/srv', '/sys', '/System', '/tmp', '/Users', '/usr', '/usr/X11R6', '/usr/bin', '/usr/include', '/usr/lib', '/usr/libdata', '/usr/libexec', '/usr/local/bin', '/usr/local/src', '/usr/obj', '/usr/ports', '/usr/sbin', '/usr/share', '/usr/src', '/var', '/var/log', '/var/mail', '/var/spool', '/var/tmp', '/var/yp' ] // generators for $random* variables this.dynamicGenerators = { // Skipped from Postman $guid: { description: 'A v4 style guid', generator: function () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { const r = (Math.random() * 16) | 0 const v = c === 'x' ? r : (r & 0x3) | 0x8 return v.toString(16) }) } }, $timestamp: { description: 'The current timestamp', generator: function () { return Math.round(Date.now() / 1000) } }, $isoTimestamp: { description: 'The current ISO timestamp at zero UTC', generator: function () { return new Date().toISOString() } }, $randomInt: { description: 'A random integer between 0 and 1000', generator: function () { return ~~(Math.random() * (1000 + 1)) } }, // faker.phone.phoneNumber returns phone number with or without // extension randomly. this only returns a phone number without extension. $randomPhoneNumber: { description: 'A random 10-digit phone number', generator: function () { return faker.phone.phoneNumberFormat(0) } }, // faker.phone.phoneNumber returns phone number with or without // extension randomly. this only returns a phone number with extension. $randomPhoneNumberExt: { description: 'A random phone number with extension (12 digits)', generator: function () { return faker.datatype.number({ min: 1, max: 99 }) + '-' + faker.phone.phoneNumberFormat(0) } }, // faker's random.locale only returns 'en'. this returns from a list of // random locales $randomLocale: { description: 'A random two-letter language code (ISO 639-1)', generator: function () { return faker.random.arrayElement(LOCALES) as string } }, // fakers' random.words returns random number of words between 1, 3. // this returns number of words between 2, 5. $randomWords: { description: 'Some random words', generator: function () { let words = '' const count = faker.random.number({ min: 2, max: 5 }) for (let i = 0; i < count; i++) { const rndWord = faker.random.word() || '' words += rndWord } return words } }, // faker's system.filePath returns nothing. this returns a path for a file. // $randomFilePath: { // description: 'A random file path', // generator: function () { // return ( // this.dynamicGenerators.$randomDirectoryPath.generator() + '/' + faker.system.fileName() // ) // } // }, // faker's system.directoryPath returns nothing. this returns a path for a directory. $randomDirectoryPath: { description: 'A random directory path', generator: function () { return faker.random.arrayElement(DIRECTORY_PATHS) } }, $randomCity: { description: 'A random city name', generator: faker.address.city }, $randomStreetName: { description: 'A random street name', generator: faker.address.streetName }, $randomStreetAddress: { description: 'A random street address (e.g. 1234 Main Street)', generator: faker.address.streetAddress }, $randomCountry: { description: 'A random country', generator: faker.address.country }, $randomCountryCode: { description: 'A random 2-letter country code (ISO 3166-1 alpha-2)', generator: faker.address.countryCode }, $randomLatitude: { description: 'A random latitude coordinate', generator: faker.address.latitude }, $randomLongitude: { description: 'A random longitude coordinate', generator: faker.address.longitude }, $randomColor: { description: 'A random color', generator: faker.commerce.color }, $randomDepartment: { description: 'A random commerce category (e.g. electronics, clothing)', generator: faker.commerce.department }, $randomProductName: { description: 'A random product name (e.g. handmade concrete tuna)', generator: faker.commerce.productName }, $randomProductAdjective: { description: 'A random product adjective (e.g. tasty, eco-friendly)', generator: faker.commerce.productAdjective }, $randomProductMaterial: { description: 'A random product material (e.g. steel, plastic, leather)', generator: faker.commerce.productMaterial }, $randomProduct: { description: 'A random product (e.g. shoes, table, chair)', generator: faker.commerce.product }, $randomCompanyName: { description: 'A random company name', generator: faker.company.companyName }, $randomCompanySuffix: { description: 'A random company suffix (e.g. Inc, LLC, Group)', generator: faker.company.companySuffix }, $randomCatchPhrase: { description: 'A random catchphrase', generator: faker.company.catchPhrase }, $randomBs: { description: 'A random phrase of business speak', generator: faker.company.bs }, $randomCatchPhraseAdjective: { description: 'A random catchphrase adjective', generator: faker.company.catchPhraseAdjective }, $randomCatchPhraseDescriptor: { description: 'A random catchphrase descriptor', generator: faker.company.catchPhraseDescriptor }, $randomCatchPhraseNoun: { description: 'Randomly generates a catchphrase noun', generator: faker.company.catchPhraseNoun }, $randomBsAdjective: { description: 'A random business speak adjective', generator: faker.company.bsAdjective }, $randomBsBuzz: { description: 'A random business speak buzzword', generator: faker.company.bsBuzz }, $randomBsNoun: { description: 'A random business speak noun', generator: faker.company.bsNoun }, $randomDatabaseColumn: { description: 'A random database column name (e.g. updatedAt, token, group)', generator: faker.database.column }, $randomDatabaseType: { description: 'A random database type (e.g. tiny int, double, point)', generator: faker.database.type }, $randomDatabaseCollation: { description: 'A random database collation (e.g. cp1250_bin)', generator: faker.database.collation }, $randomDatabaseEngine: { description: 'A random database engine (e.g. Memory, Archive, InnoDB)', generator: faker.database.engine }, $randomDatePast: { description: 'A random past datetime', generator: faker.date.past }, $randomDateFuture: { description: 'A random future datetime', generator: faker.date.future }, $randomDateRecent: { description: 'A random recent datetime', generator: faker.date.recent }, $randomMonth: { description: 'A random month', generator: faker.date.month }, $randomWeekday: { description: 'A random weekday', generator: faker.date.weekday }, $randomBankAccount: { description: 'A random 8-digit bank account number', generator: faker.finance.account }, $randomBankAccountName: { description: 'A random bank account name (e.g. savings account, checking account)', generator: faker.finance.accountName }, $randomCreditCardMask: { description: 'A random masked credit card number', generator: faker.finance.mask }, $randomPrice: { description: 'A random price between 0.00 and 1000.00', generator: faker.finance.amount }, $randomTransactionType: { description: 'A random transaction type (e.g. invoice, payment, deposit)', generator: faker.finance.transactionType }, $randomCurrencyCode: { description: 'A random 3-letter currency code (ISO-4217)', generator: faker.finance.currencyCode }, $randomCurrencyName: { description: 'A random currency name', generator: faker.finance.currencyName }, $randomCurrencySymbol: { description: 'A random currency symbol', generator: faker.finance.currencySymbol }, $randomBitcoin: { description: 'A random bitcoin address', generator: faker.finance.bitcoinAddress }, $randomBankAccountIban: { description: 'A random 15-31 character IBAN (International Bank Account Number)', generator: faker.finance.iban }, $randomBankAccountBic: { description: 'A random BIC (Bank Identifier Code)', generator: faker.finance.bic }, $randomAbbreviation: { description: 'A random abbreviation', generator: faker.hacker.abbreviation }, $randomAdjective: { description: 'A random adjective', generator: faker.hacker.adjective }, $randomNoun: { description: 'A random noun', generator: faker.hacker.noun }, $randomVerb: { description: 'A random verb', generator: faker.hacker.verb }, $randomIngverb: { description: 'A random verb ending in “-ing”', generator: faker.hacker.ingverb }, $randomPhrase: { description: 'A random phrase', generator: faker.hacker.phrase }, $randomAvatarImage: { description: 'A random avatar image', generator: faker.image.avatar }, $randomImageUrl: { description: 'A URL for a random image', generator: faker.image.imageUrl }, $randomAbstractImage: { description: 'A URL for a random abstract image', generator: faker.image.abstract }, $randomAnimalsImage: { description: 'A URL for a random animal image', generator: faker.image.animals }, $randomBusinessImage: { description: 'A URL for a random stock business image', generator: faker.image.business }, $randomCatsImage: { description: 'A URL for a random cat image', generator: faker.image.cats }, $randomCityImage: { description: 'A URL for a random city image', generator: faker.image.city }, $randomFoodImage: { description: 'A URL for a random food image', generator: faker.image.food }, $randomNightlifeImage: { description: 'A URL for a random nightlife image', generator: faker.image.nightlife }, $randomFashionImage: { description: 'A URL for a random fashion image', generator: faker.image.fashion }, $randomPeopleImage: { description: 'A URL for a random image of a person', generator: faker.image.people }, $randomNatureImage: { description: 'A URL for a random nature image', generator: faker.image.nature }, $randomSportsImage: { description: 'A URL for a random sports image', generator: faker.image.sports }, $randomTransportImage: { description: 'A URL for a random transportation image', generator: faker.image.transport }, $randomImageDataUri: { description: 'A random image data URI', generator: faker.image.dataUri }, $randomEmail: { description: 'A random email address', generator: faker.internet.email }, $randomExampleEmail: { description: 'A random email address from an “example” domain (e.g. ben@example.com)', generator: faker.internet.exampleEmail }, $randomUserName: { description: 'A random username', generator: faker.internet.userName }, $randomProtocol: { description: 'A random internet protocol', generator: faker.internet.protocol }, $randomUrl: { description: 'A random URL', generator: faker.internet.url }, $randomDomainName: { description: 'A random domain name (e.g. gracie.biz, trevor.info)', generator: faker.internet.domainName }, $randomDomainSuffix: { description: 'A random domain suffix (e.g. .com, .net, .org)', generator: faker.internet.domainSuffix }, $randomDomainWord: { description: 'A random unqualified domain name (a name with no dots)', generator: faker.internet.domainWord }, $randomIP: { description: 'A random IPv4 address', generator: faker.internet.ip }, $randomIPV6: { description: 'A random IPv6 address', generator: faker.internet.ipv6 }, $randomUserAgent: { description: 'A random user agent', generator: faker.internet.userAgent }, $randomHexColor: { description: 'A random hex value', generator: faker.internet.color }, $randomMACAddress: { description: 'A random MAC address', generator: faker.internet.mac }, $randomPassword: { description: 'A random 15-character alpha-numeric password', generator: faker.internet.password }, $randomLoremWord: { description: 'A random word of lorem ipsum text', generator: faker.lorem.word }, $randomLoremWords: { description: 'Some random words of lorem ipsum text', generator: faker.lorem.words }, $randomLoremSentence: { description: 'A random sentence of lorem ipsum text', generator: faker.lorem.sentence }, $randomLoremSlug: { description: 'A random lorem ipsum URL slug', generator: faker.lorem.slug }, $randomLoremSentences: { description: 'A random 2-6 sentences of lorem ipsum text', generator: faker.lorem.sentences }, $randomLoremParagraph: { description: 'A random paragraph of lorem ipsum text', generator: faker.lorem.paragraph }, $randomLoremParagraphs: { description: '3 random paragraphs of lorem ipsum text', generator: faker.lorem.paragraphs }, $randomLoremText: { description: 'A random amount of lorem ipsum text', generator: faker.lorem.text }, $randomLoremLines: { description: '1-5 random lines of lorem ipsum', generator: faker.lorem.lines }, $randomFirstName: { description: 'A random first name', generator: faker.name.firstName }, $randomLastName: { description: 'A random last name', generator: faker.name.lastName }, $randomFullName: { description: 'A random first and last name', generator: faker.name.findName }, $randomJobTitle: { description: 'A random job title (e.g. senior software developer)', generator: faker.name.jobTitle }, $randomNamePrefix: { description: 'A random name prefix (e.g. Mr., Mrs., Dr.)', generator: faker.name.prefix }, $randomNameSuffix: { description: 'A random name suffix (e.g. Jr., MD, PhD)', generator: faker.name.suffix }, $randomJobDescriptor: { description: 'A random job descriptor (e.g., senior, chief, corporate, etc.)', generator: faker.name.jobDescriptor }, $randomJobArea: { description: 'A random job area (e.g. branding, functionality, usability)', generator: faker.name.jobArea }, $randomJobType: { description: 'A random job type (e.g. supervisor, manager, coordinator, etc.)', generator: faker.name.jobType }, $randomUUID: { description: 'A random 36-character UUID', generator: faker.datatype.uuid }, $randomBoolean: { description: 'A random boolean value (true/false)', generator: faker.datatype.boolean }, $randomWord: { description: 'A random word', generator: faker.random.word }, $randomAlphaNumeric: { description: 'A random alpha-numeric character', generator: faker.random.alphaNumeric }, $randomFileName: { description: 'A random file name (includes uncommon extensions)', generator: faker.system.fileName }, $randomCommonFileName: { description: 'A random file name', generator: faker.system.commonFileName }, $randomMimeType: { description: 'A random MIME type', generator: faker.system.mimeType }, $randomCommonFileType: { description: 'A random, common file type (e.g., video, text, image, etc.)', generator: faker.system.commonFileType }, $randomCommonFileExt: { description: 'A random, common file extension (.doc, .jpg, etc.)', generator: faker.system.commonFileExt }, $randomFileType: { description: 'A random file type (includes uncommon file types)', generator: faker.system.fileType }, $randomFileExt: { description: 'A random file extension (includes uncommon extensions)', generator: faker.system.fileExt }, $randomSemver: { description: 'A random semantic version number', generator: faker.system.semver }, $randomIntTest: { description: 'Return 123 (for testing purposes', generator: function () { return 123 } } } } // Build a regex matching the dynamicGenerators // It will look like this: /\{\{\$guid\}\}|\{\{\$timestamp\}\}|\{\{\$isoTimestamp\}\}/g public dynamicGeneratorsRegex(): RegExp { let generatorRegexString = '' Object.entries(this.dynamicGenerators).forEach(([key]) => { generatorRegexString += '{{' + key + '}}' + '|' }) // Remove the trailing '|' generatorRegexString = generatorRegexString.slice(0, -1) // Escape the special regex characters we can find in generator name. Method inspired by: // https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript/3561711#3561711 generatorRegexString = generatorRegexString.replace(/[${}]/g, '\\$&') return new RegExp(generatorRegexString, 'g') } public replaceDynamicVar(value: string): string { const dynamicRegex = this.dynamicGeneratorsRegex() return value.replace(dynamicRegex, match => { // We remove the enclosing {{ }} to extract the generator type like "$randomName" const generatorType = match.slice(2, -2) return this.dynamicGenerators[generatorType].generator() }) } public renderDynamicVar(dynamicVariable: string): any { const functionName = '$' + dynamicVariable if (this.dynamicGenerators[functionName]) { return this.dynamicGenerators[functionName].generator() } else { throw new Error(`Unsupported Postman dynamic variable: ${dynamicVariable}`) } } }
the_stack
const code_CarriageReturn = "\r".charCodeAt(0); const code_NewLine = "\n".charCodeAt(0); const code_Space = " ".charCodeAt(0); const code_Tab = "\t".charCodeAt(0); const code_Slash = "/".charCodeAt(0); const code_Backslash = "\\".charCodeAt(0); const code_Star = "*".charCodeAt(0); const code_Hash = "#".charCodeAt(0); const code_Bang = "!".charCodeAt(0); const code_SingleQuote = "'".charCodeAt(0); const code_DoubleQuote = "\"".charCodeAt(0); const code_OpenBrace = "{".charCodeAt(0); const code_CloseBrace = "}".charCodeAt(0); const code_OpenBracket = "[".charCodeAt(0); const code_CloseBracket = "]".charCodeAt(0); const code_Backtick = "`".charCodeAt(0); const code_Dollar = "$".charCodeAt(0); const enum State { Uninitialized, Default, StartSingleLineComment, SingleLineComment, StartMultiLineComment, MultiLineComment, EndMultiLineComment, StartShebangComment, ShebangComment, SingleQuoteString, SingleQuoteStringEscapeBackslash, SingleQuoteStringEscapeQuote, DoubleQuoteString, DoubleQuoteStringEscapeBackslash, DoubleQuoteStringEscapeQuote, TemplateString, TemplateStringEscapeBackslash, TemplateStringEscapeQuote, StartExpressionHole, Regex, RegexEscapeBackslash, RegexEscapeSlash, RegexEscapeOpenBracket, CharClass, CharClassEscapeBackslash, CharClassEscapeCloseBracket, } export type CharKind = | "whitespace" | "comment" | "string" | "regex" | "code" ; interface StepResult { charKind: CharKind; wrapLine: boolean; } export interface StateMachine { step(ch: number, nextCh: number): StepResult; } export function create(): StateMachine { let state = State.Default; let braceDepth = 0; let templateStringBraceDepthStack: number[] = []; let isBOF = true; function step(ch: number, nextCh: number): StepResult { let nextStateId = State.Uninitialized;; let wrapLine = false; switch (ch) { case code_CarriageReturn: if (nextCh === code_NewLine) { if (state === State.ShebangComment || state === State.SingleLineComment || // Cases below are for error recovery state === State.SingleQuoteString || state === State.DoubleQuoteString || state === State.Regex || state === State.CharClass) { state = State.Default; } break; } // Fall through case code_NewLine: wrapLine = true; if (state === State.ShebangComment || state === State.SingleLineComment) { state = State.Default; } else if (state === State.SingleQuoteString || // Error recovery state === State.DoubleQuoteString) { // Error recovery state = State.Default; } break; case code_Slash: if (state === State.Default) { if (nextCh === code_Slash) { state = State.StartSingleLineComment; } else if (nextCh === code_Star) { // It seems like there might technically be a corner case where this is the beginning of an invalid regex state = State.StartMultiLineComment; } else { // TODO (https://github.com/microsoft/typescript-analyze-trace/issues/14): this is too aggressive - it will catch division state = State.Regex; } } else if (state === State.StartSingleLineComment) { state = State.SingleLineComment; } else if (state === State.EndMultiLineComment) { nextStateId = State.Default; } else if (state === State.Regex) { nextStateId = State.Default; } else if (state === State.RegexEscapeSlash) { nextStateId = State.Regex; } break; case code_Star: if (state === State.StartMultiLineComment) { state = State.MultiLineComment; } else if (state === State.MultiLineComment) { if (nextCh === code_Slash) { state = State.EndMultiLineComment; } } break; case code_Hash: if (isBOF && state === State.Default && nextCh === code_Bang) { state = State.StartShebangComment; } break; case code_Bang: if (state === State.StartShebangComment) { state = State.ShebangComment; } break; case code_SingleQuote: if (state === State.Default) { state = State.SingleQuoteString; } else if (state === State.SingleQuoteStringEscapeQuote) { nextStateId = State.SingleQuoteString; } else if (state === State.SingleQuoteString) { nextStateId = State.Default; } break; case code_DoubleQuote: if (state === State.Default) { state = State.DoubleQuoteString; } else if (state === State.DoubleQuoteStringEscapeQuote) { nextStateId = State.DoubleQuoteString; } else if (state === State.DoubleQuoteString) { nextStateId = State.Default; } break; case code_Backtick: if (state === State.Default) { state = State.TemplateString; } else if (state === State.TemplateStringEscapeQuote) { nextStateId = State.TemplateString; } else if (state === State.TemplateString) { nextStateId = State.Default; } break; case code_Backslash: if (state === State.SingleQuoteString) { if (nextCh === code_SingleQuote) { state = State.SingleQuoteStringEscapeQuote; } else if (nextCh === code_Backslash) { state = State.SingleQuoteStringEscapeBackslash; } } else if (state === State.DoubleQuoteString) { if (nextCh === code_DoubleQuote) { state = State.DoubleQuoteStringEscapeQuote; } else if (nextCh === code_Backslash) { state = State.DoubleQuoteStringEscapeBackslash; } } else if (state === State.TemplateString) { if (nextCh === code_Backtick) { state = State.TemplateStringEscapeQuote; } else if (nextCh === code_Backslash) { state = State.TemplateStringEscapeBackslash; } } else if (state === State.Regex) { if (nextCh === code_OpenBracket) { state = State.RegexEscapeOpenBracket; } else if (nextCh === code_Slash) { state = State.RegexEscapeSlash; } else if (nextCh === code_Backslash) { state = State.RegexEscapeBackslash; } } else if (state === State.CharClass) { if (nextCh === code_CloseBracket) { state = State.CharClassEscapeCloseBracket; } else if (nextCh === code_Backslash) { state = State.CharClassEscapeBackslash; } } else if (state === State.SingleQuoteStringEscapeBackslash) { nextStateId = State.SingleQuoteString; } else if (state === State.DoubleQuoteStringEscapeBackslash) { nextStateId = State.DoubleQuoteString; } else if (state === State.TemplateStringEscapeBackslash) { nextStateId = State.TemplateString; } else if (state === State.RegexEscapeBackslash) { nextStateId = State.Regex; } else if (state === State.CharClassEscapeBackslash) { nextStateId = State.CharClass; } break; case code_Dollar: if (state === State.TemplateString && nextCh === code_OpenBrace) { state = State.StartExpressionHole; } break; case code_OpenBrace: if (state === State.Default) { braceDepth++; } else if (state === State.StartExpressionHole) { templateStringBraceDepthStack.push(braceDepth); nextStateId = State.Default; } break; case code_CloseBrace: if (templateStringBraceDepthStack.length && braceDepth === templateStringBraceDepthStack[templateStringBraceDepthStack.length - 1]) { templateStringBraceDepthStack.pop(); state = State.TemplateString; } else if (state === State.Default && braceDepth > 0) { // Error recovery braceDepth--; } break; case code_OpenBracket: if (state === State.RegexEscapeOpenBracket) { nextStateId = State.Regex; } else if (state === State.Regex) { state = State.CharClass; } break; case code_CloseBracket: if (state === State.CharClassEscapeCloseBracket) { nextStateId = State.CharClass; } else if (state === State.CharClass) { nextStateId = State.Regex; } break; } let charKind: CharKind; switch (state) { case State.StartSingleLineComment: case State.SingleLineComment: case State.StartMultiLineComment: case State.MultiLineComment: case State.EndMultiLineComment: case State.StartShebangComment: case State.ShebangComment: charKind = "comment"; break; case State.SingleQuoteString: case State.SingleQuoteStringEscapeBackslash: case State.SingleQuoteStringEscapeQuote: case State.DoubleQuoteString: case State.DoubleQuoteStringEscapeBackslash: case State.DoubleQuoteStringEscapeQuote: case State.TemplateString: case State.TemplateStringEscapeBackslash: case State.TemplateStringEscapeQuote: case State.StartExpressionHole: charKind = "string"; break; case State.Regex: case State.RegexEscapeBackslash: case State.RegexEscapeSlash: case State.RegexEscapeOpenBracket: case State.CharClass: case State.CharClassEscapeBackslash: case State.CharClassEscapeCloseBracket: charKind = "regex"; break; default: const isWhitespace = ch === code_Space || ch === code_Tab || ch === code_NewLine || ch === code_CarriageReturn || /^\s$/.test(String.fromCharCode(ch)); charKind = isWhitespace ? "whitespace" : "code"; break; } if (nextStateId !== State.Uninitialized) { state = nextStateId; } isBOF = false; return { charKind, wrapLine }; } return { step }; }
the_stack
import moment = require("moment"); import { BasicClient } from "../BasicClient"; import { Candle } from "../Candle"; import { CandlePeriod } from "../CandlePeriod"; import { ClientOptions } from "../ClientOptions"; import { CancelableFn } from "../flowcontrol/Fn"; import { throttle } from "../flowcontrol/Throttle"; import { Level2Point } from "../Level2Point"; import { Level2Snapshot } from "../Level2Snapshots"; import { Level2Update } from "../Level2Update"; import { NotImplementedFn } from "../NotImplementedFn"; import { SmartWss } from "../SmartWss"; import { Ticker } from "../Ticker"; import { Trade } from "../Trade"; import { wait } from "../Util"; import * as https from "../Https"; import * as zlib from "../ZlibUtils"; /** * Implements the v3 API: * https://bittrex.github.io/api/v3#topic-Synchronizing * https://bittrex.github.io/guides/v3/upgrade * * This client uses SignalR and requires a custom connection strategy to * obtain a socket. Otherwise, things are relatively the same vs a * standard client. */ export class BittrexClient extends BasicClient { public candlePeriod: CandlePeriod; public orderBookDepth: number; public connectInitTimeoutMs: number; protected _subbedTickers: boolean; protected _messageId: number; protected _requestLevel2Snapshot: CancelableFn; protected _sendSubLevel2Snapshots = NotImplementedFn; protected _sendUnsubLevel2Snapshots = NotImplementedFn; protected _sendSubLevel3Snapshots = NotImplementedFn; protected _sendUnsubLevel3Snapshots = NotImplementedFn; protected _sendSubLevel3Updates = NotImplementedFn; protected _sendUnsubLevel3Updates = NotImplementedFn; constructor({ wssPath, watcherMs = 15000, throttleL2Snapshot = 100 }: ClientOptions = {}) { super(wssPath, "Bittrex", undefined, watcherMs); this.hasTickers = true; this.hasTrades = true; this.hasCandles = true; this.hasLevel2Snapshots = false; this.hasLevel2Updates = true; this.hasLevel3Snapshots = false; this.hasLevel3Updates = false; this.candlePeriod = CandlePeriod._1m; this.orderBookDepth = 500; this.connectInitTimeoutMs = 5000; this._subbedTickers = false; this._messageId = 0; this._processTickers = this._processTickers.bind(this); this._processTrades = this._processTrades.bind(this); this._processCandles = this._processCandles.bind(this); this._processLevel2Update = this._processLevel2Update.bind(this); this._requestLevel2Snapshot = throttle( this.__requestLevel2Snapshot.bind(this), throttleL2Snapshot, ); } //////////////////////////////////// // PROTECTED protected _beforeConnect() { this._wss.on("connected", () => this._sendHeartbeat()); } protected _beforeClose() { this._subbedTickers = false; this._requestLevel2Snapshot.cancel(); } protected _sendHeartbeat() { this._wss.send( JSON.stringify({ H: "c3", M: "Subscribe", A: [["heartbeat"]], I: ++this._messageId, }), ); } protected _sendSubTicker() { if (this._subbedTickers) return; this._subbedTickers = true; this._wss.send( JSON.stringify({ H: "c3", M: "Subscribe", A: [["market_summaries"]], I: ++this._messageId, }), ); } protected _sendUnsubTicker() { // no-op } protected _sendSubTrades(remote_id) { this._wss.send( JSON.stringify({ H: "c3", M: "Subscribe", A: [[`trade_${remote_id}`]], I: ++this._messageId, }), ); } protected _sendUnsubTrades(remote_id) { this._wss.send( JSON.stringify({ H: "c3", M: "Unsubscribe", A: [[`trade_${remote_id}`]], I: ++this._messageId, }), ); } protected _sendSubCandles(remote_id) { this._wss.send( JSON.stringify({ H: "c3", M: "Subscribe", A: [[`candle_${remote_id}_${candlePeriod(this.candlePeriod)}`]], I: ++this._messageId, }), ); } protected _sendUnsubCandles(remote_id) { this._wss.send( JSON.stringify({ H: "c3", M: "Unsubscribe", A: [[`candle_${remote_id}_${candlePeriod(this.candlePeriod)}`]], I: ++this._messageId, }), ); } protected _sendSubLevel2Updates(remote_id, market) { this._requestLevel2Snapshot(market); this._wss.send( JSON.stringify({ H: "c3", M: "Subscribe", A: [[`orderbook_${remote_id}_${this.orderBookDepth}`]], I: ++this._messageId, }), ); } protected _sendUnsubLevel2Updates(remote_id) { this._wss.send( JSON.stringify({ H: "c3", M: "Subscribe", A: [[`orderbook_${remote_id}_${this.orderBookDepth}`]], I: ++this._messageId, }), ); } /** * Requires connecting to SignalR which has a whole BS negotiation * to obtain a token, similar to Kucoin actually. */ protected _connect() { if (!this._wss) { this._wss = { status: "connecting" } as any; this._connectAsync(); } } /** * Asynchronously connect to a socket. This method will retrieve a token * from an HTTP request and then construct a websocket. If the HTTP * request fails, it will retry until successful. */ protected async _connectAsync() { let wssPath = this.wssPath; // Retry HTTP requests until we are successful while (!wssPath) { try { const data = JSON.stringify([{ name: "c3" }]); const negotiations: any = await https.get( `https://socket-v3.bittrex.com/signalr/negotiate?connectionData=${data}&clientProtocol=1.5`, ); const token = encodeURIComponent(negotiations.ConnectionToken); wssPath = `wss://socket-v3.bittrex.com/signalr/connect?clientProtocol=1.5&transport=webSockets&connectionToken=${token}&connectionData=${data}&tid=10`; } catch (ex) { await wait(this.connectInitTimeoutMs); this._onError(ex); } } // Construct a socket and bind all events const wss = new SmartWss(wssPath); this._wss = wss; this._wss.on("error", this._onError.bind(this)); this._wss.on("connecting", this._onConnecting.bind(this)); this._wss.on("connected", this._onConnected.bind(this)); this._wss.on("disconnected", this._onDisconnected.bind(this)); this._wss.on("closing", this._onClosing.bind(this)); this._wss.on("closed", this._onClosed.bind(this)); this._wss.on("message", msg => { try { this._onMessage(msg); } catch (ex) { this._onError(ex); } }); if (this._beforeConnect) this._beforeConnect(); this._wss.connect(); } protected _onMessage(raw) { const fullMsg = JSON.parse(raw); // Handle responses // {"R":[{"Success":true,"ErrorCode":null},{"Success":true,"ErrorCode":null}],"I":1} if (fullMsg.R) { for (const msg of fullMsg.R) { if (!msg.Success) { this.emit( "error", new Error("Subscription failed with error " + msg.ErrorCode), ); } } } // Handle messages if (!fullMsg.M) return; for (const msg of fullMsg.M) { if (msg.M === "heartbeat") { this._watcher.markAlive(); } if (msg.M === "marketSummaries") { for (const a of msg.A) { zlib.inflateRaw(Buffer.from(a, "base64"), this._processTickers); } } if (msg.M === "trade") { for (const a of msg.A) { zlib.inflateRaw(Buffer.from(a, "base64"), this._processTrades); } } if (msg.M === "candle") { for (const a of msg.A) { zlib.inflateRaw(Buffer.from(a, "base64"), this._processCandles); } } if (msg.M === "orderBook") { for (const a of msg.A) { zlib.inflateRaw(Buffer.from(a, "base64"), this._processLevel2Update); } } } } /** { "sequence": 3584000, "deltas": [ { symbol: 'BTC-USDT', high: '12448.02615735', low: '11773.32163568', volume: '640.86060471', quoteVolume: '7714634.67704918', percentChange: '3.98', updatedAt: '2020-08-17T20:16:27.617Z' } ] } */ protected _processTickers(err, raw) { if (err) { this.emit("error", err); return; } let msg; try { msg = JSON.parse(raw); } catch (ex) { this.emit("error", ex); return; } for (const datum of msg.deltas) { const market = this._tickerSubs.get(datum.symbol); if (!market) continue; const ticker = this._constructTicker(datum, market); this.emit("ticker", ticker, market); } } protected _constructTicker(msg, market) { const { high, low, volume, quoteVolume, percentChange, updatedAt } = msg; return new Ticker({ exchange: this.name, base: market.base, quote: market.quote, timestamp: moment.utc(updatedAt).valueOf(), last: undefined, open: undefined, high: high, low: low, volume: volume, quoteVolume: quoteVolume, change: undefined, changePercent: percentChange, bid: undefined, ask: undefined, }); } /** { deltas: [ { id: 'edacd990-7c5f-4c75-8a66-ce0a71093b3c', executedAt: '2020-08-17T20:36:39.96Z', quantity: '0.00714818', rate: '12301.34800000', takerSide: 'BUY' } ], sequence: 18344, marketSymbol: 'BTC-USDT' } */ protected _processTrades(err, raw) { if (err) { this.emit("error", err); return; } let msg; try { msg = JSON.parse(raw); } catch (ex) { this.emit("error", ex); return; } const market = this._tradeSubs.get(msg.marketSymbol); if (!market) return; for (const datum of msg.deltas) { const trade = this._constructTrade(datum, market); this.emit("trade", trade, market); } } protected _constructTrade(msg, market) { const tradeId = msg.id; const unix = moment.utc(msg.executedAt).valueOf(); const price = msg.rate; const amount = msg.quantity; const side = msg.takerSide === "BUY" ? "buy" : "sell"; return new Trade({ exchange: this.name, base: market.base, quote: market.quote, tradeId, unix, side, price, amount, }); } /** { sequence: 10808, marketSymbol: 'BTC-USDT', interval: 'MINUTE_1', delta: { startsAt: '2020-08-17T20:47:00Z', open: '12311.59599999', high: '12311.59599999', low: '12301.57150000', close: '12301.57150000', volume: '1.65120614', quoteVolume: '20319.96359337' } } */ protected _processCandles(err, raw) { if (err) { this.emit("error", err); return; } let msg; try { msg = JSON.parse(raw); } catch (ex) { this.emit("error", ex); return; } const market = this._candleSubs.get(msg.marketSymbol); if (!market) return; const candle = this._constructCandle(msg.delta); this.emit("candle", candle, market); } protected _constructCandle(msg) { return new Candle( moment.utc(msg.startsAt).valueOf(), msg.open, msg.high, msg.low, msg.close, msg.volume, ); } /** { marketSymbol: 'BTC-USDT', depth: 500, sequence: 545851, bidDeltas: [ { quantity: '0', rate: '12338.47320003' }, { quantity: '0.01654433', rate: '10800.62000000' } ], askDeltas: [] } */ protected _processLevel2Update(err, raw) { if (err) { this.emit("error", err); return; } let msg; try { msg = JSON.parse(raw); } catch (ex) { this.emit("error", ex); return; } const market = this._level2UpdateSubs.get(msg.marketSymbol); if (!market) return; const update = this._constructLevel2Update(msg, market); this.emit("l2update", update, market); } protected _constructLevel2Update(msg, market) { const sequenceId = msg.sequence; const depth = msg.depth; const bids = msg.bidDeltas.map( p => new Level2Point(p.rate, p.quantity, undefined, { depth }), ); const asks = msg.askDeltas.map( p => new Level2Point(p.rate, p.quantity, undefined, { depth }), ); return new Level2Update({ exchange: this.name, base: market.base, quote: market.quote, sequenceId, asks, bids, }); } protected async __requestLevel2Snapshot(market) { let failed: any; try { const remote_id = market.id; const uri = `https://api.bittrex.com/v3/markets/${remote_id}/orderbook?depth=${this.orderBookDepth}`; const { data, response } = await https.getResponse<any>(uri); const raw = data; const sequence = +response.headers.sequence; const asks = raw.ask.map(p => new Level2Point(p.rate, p.quantity)); const bids = raw.bid.map(p => new Level2Point(p.rate, p.quantity)); const snapshot = new Level2Snapshot({ exchange: this.name, base: market.base, quote: market.quote, sequenceId: sequence, asks, bids, }); this.emit("l2snapshot", snapshot, market); } catch (ex) { const err = new Error("L2Snapshot failed") as any; err.inner = ex.message; err.market = market; this.emit("error", err); failed = err; } finally { if (failed && failed.inner.indexOf("MARKET_DOES_NOT_EXIST") === -1) { this._requestLevel2Snapshot(market); } } } } function candlePeriod(period) { switch (period) { case CandlePeriod._1m: return "MINUTE_1"; case CandlePeriod._5m: return "MINUTE_5"; case CandlePeriod._1h: return "HOUR_1"; case CandlePeriod._1d: return "DAY_1"; } }
the_stack
function test_dropdown_static() { $.fn.dropdown.settings.error!.method = 'method'; $.fn.dropdown.settings.namespace = 'namespace'; $.fn.dropdown.settings.name = 'name'; $.fn.dropdown.settings.silent = false; $.fn.dropdown.settings.debug = true; $.fn.dropdown.settings.performance = true; $.fn.dropdown.settings.verbose = true; } function test_dropdown() { const selector = '.ui.dropdown'; $(selector).dropdown('setup menu'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('refresh'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('toggle'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('show'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('hide'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('clear'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('hide others'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('restore defaults'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('restore default text'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('restore placeholder text'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('restore default value'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('save defaults'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('set selected', 123); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('remove selected', false); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('set selected', ['456']); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('set exactly', []); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('set text', 'hello'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('set value', 24); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('get text'); // $ExpectType string $(selector).dropdown('get value'); // $ExpectType any $(selector).dropdown('get item', 'Pennsylvania'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('bind touch events'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('bind mouse events'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('bind intent'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('unbind intent'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('determine intent'); // $ExpectType boolean $(selector).dropdown('determine select action', 'text', 90); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('set active'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('set visible'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('remove active'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('remove visible'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('is selection'); // $ExpectType boolean $(selector).dropdown('is animated'); // $ExpectType boolean $(selector).dropdown('is visible'); // $ExpectType boolean $(selector).dropdown('is hidden'); // $ExpectType boolean $(selector).dropdown('get default text') === 'default text'; $(selector).dropdown('get placeholder text') === 'placeholder text'; $(selector).dropdown('destroy'); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('setting', 'debug', undefined); // $ExpectType boolean $(selector).dropdown('setting', 'debug'); // $ExpectType boolean $(selector).dropdown('setting', 'debug', true); // $ExpectType JQuery<HTMLElement> // $ExpectType JQuery<HTMLElement> $(selector).dropdown('setting', { namespace: 'namespace', name: 'name', silent: false, debug: true, performance: true, verbose: true }); // $ExpectType JQuery<HTMLElement> $(selector).dropdown({ on: 'hover', allowReselection: true, allowAdditions: false, hideAdditions: true, action(text, value, element) { this; // $ExpectType JQuery<HTMLElement> text; // $ExpectType string value; // $ExpectType string | false element; // $ExpectType JQuery<HTMLElement> }, minCharacters: 2, match: 'text', selectOnKeydown: false, forceSelection: true, allowCategorySelection: false, placeholder: 'value', apiSettings: { on: 'on', cache: true, stateContext: $(), encodeParameters: false, defaultData: true, serializeForm: false, throttle: 10, throttleFirstRequest: true, interruptRequests: false, loadingDuration: 3, hideError: true, errorDuration: 10, action: 'action', url: 'url', urlData: false, response: false, responseAsync(settings, callback) { settings; // $ExpectType Param callback; // $ExpectType (response: any) => void }, mockResponse: false, mockResponseAsync(settings, callback) { settings; // $ExpectType Param callback; // $ExpectType (response: any) => void }, method: 'post', dataType: 'xml', data: {}, beforeSend(settings) { settings; // $ExpectType Param }, beforeXHR(xhrObject) { xhrObject; // $ExpectType jqXHR<any> }, onRequest(promise, xhr) { promise; // $ExpectType Deferred<any, any, any> xhr; // $ExpectType jqXHR<any> }, onResponse(response) { response; // $ExpectType any }, successTest(response) { response; // $ExpectType any return false; }, onSuccess(response, element, xhr) { response; // $ExpectType any element; // $ExpectType JQuery<HTMLElement> xhr; // $ExpectType jqXHR<any> }, onComplete(response, element, xhr) { response; // $ExpectType any element; // $ExpectType JQuery<HTMLElement> xhr; // $ExpectType jqXHR<any> }, onFailure(response, element) { response; // $ExpectType any element; // $ExpectType JQuery<HTMLElement> }, onError(errorMessage, element, xhr) { errorMessage; // $ExpectType string element; // $ExpectType JQuery<HTMLElement> xhr; // $ExpectType jqXHR<any> }, onAbort(errorMessage, element, xhr) { errorMessage; // $ExpectType string element; // $ExpectType JQuery<HTMLElement> xhr; // $ExpectType jqXHR<any> }, regExp: { required: /{\$*[A-z0-9]+}/g, optional: /{\/\$*[A-z0-9]+}/g }, selector: { disabled: '.disabled', form: 'form' }, className: { loading: 'loading', error: 'error' }, metadata: { action: 'action', url: 'url' }, error: { beforeSend: 'beforeSend', error: 'error', exitConditions: 'exitConditions', JSONParse: 'JSONParse', legacyParameters: 'legacyParameters', missingAction: 'missingAction', missingSerialize: 'missingSerialize', missingURL: 'missingURL', noReturnedValue: 'noReturnedValue', parseError: 'parseError', requiredParameter: 'requiredParameter', statusMessage: 'statusMessage', timeout: 'timeout' } }, fields: { remoteValues: 'remoteValues', values: 'values', name: 'name', value: 'value' }, saveRemoteData: true, filterRemoteData: false, useLabels: true, maxSelections: 20, glyphWidth: 14, label: { transition: 'horizontal flip', duration: 200, variation: 'basic' }, direction: 'downward', keepOnScreen: false, context: 'body', fullTextSearch: 'exact', preserveHTML: true, sortSelect: false, showOnFocus: true, allowTab: false, transition: 'auto', duration: 500, keys: { backspace: 8, delimiter: false, deleteKey: 46, enter: 13, escape: 27, pageUp: 33, pageDown: 34, leftArrow: 37, upArrow: 38, rightArrow: 30, downArrow: 40 }, delay: { hide: 300, show: 200, search: 50, touch: 50 }, onChange(value, text, $choice) { value; // $ExpectType any text; // $ExpectType string $choice; // $ExpectType JQuery<HTMLElement> }, onAdd(addedValue, addedText, $addedChoice) { addedValue; // $ExpectType any addedText; // $ExpectType string $addedChoice; // $ExpectType JQuery<HTMLElement> }, message: { addResult: 'addResult', count: 'count', maxSelections: 'maxSelections', noResults: 'noResults', }, selector: { addition: 'addition', dropdown: 'dropdown', icon: 'icon', input: 'input', item: 'item', label: 'label', remove: 'remove', siblingLabel: 'siblingLabel', menu: 'menu', message: 'message', menuIcon: 'menuIcon', search: 'search', text: 'text', }, regExp: { escape: /[-[\]{}()*+?.,\\^$|#\s]/g }, metadata: { defaultText: 'defaultText', defaultValue: 'defaultValue', placeholderText: 'placeholderText', text: 'text', value: 'value', }, className: { active: 'active', addition: 'addition', animating: 'animating', disabled: 'disabled', dropdown: 'dropdown', filtered: 'filtered', hidden: 'hidden', item: 'item', label: 'label', loading: 'loading', menu: 'menu', message: 'message', multiple: 'multiple', placeholder: 'placeholder', search: 'search', selected: 'selected', selection: 'selection', upward: 'upward', visible: 'visible', }, error: { action: 'action', alreadySetup: 'alreadySetup', labels: 'labels', method: 'method', noTransition: 'noTransition' } }); $(selector).dropdown(); // $ExpectType JQuery<HTMLElement> $(selector).dropdown('foo'); // $ExpectError $(selector).dropdown({ foo: 'bar' }); // $ExpectError } import dropdown = require('semantic-ui-dropdown'); function test_module() { dropdown; // $ExpectType Dropdown $.fn.dropdown = dropdown; }
the_stack
import { Injectable } from '@angular/core'; import { CoreError } from '@classes/errors/error'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreCourseCommonModWSOptions } from '@features/course/services/course'; import { CoreCourseLogHelper } from '@features/course/services/log-helper'; import { CoreApp } from '@services/app'; import { CoreFilepool } from '@services/filepool'; import { CoreSites, CoreSitesCommonWSOptions } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreStatusWithWarningsWSResponse, CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton } from '@singletons'; import { AddonModSurveyOffline } from './survey-offline'; const ROOT_CACHE_KEY = 'mmaModSurvey:'; /** * Service that provides some features for surveys. */ @Injectable( { providedIn: 'root' }) export class AddonModSurveyProvider { static readonly COMPONENT = 'mmaModSurvey'; /** * Get a survey's questions. * * @param surveyId Survey ID. * @param options Other options. * @return Promise resolved when the questions are retrieved. */ async getQuestions(surveyId: number, options: CoreCourseCommonModWSOptions = {}): Promise<AddonModSurveyQuestion[]> { const site = await CoreSites.getSite(options.siteId); const params: AddonModSurveyGetQuestionsWSParams = { surveyid: surveyId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getQuestionsCacheKey(surveyId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModSurveyProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read<AddonModSurveyGetQuestionsWSResponse>('mod_survey_get_questions', params, preSets); if (response.questions) { return response.questions; } throw new CoreError('No questions were found.'); } /** * Get cache key for survey questions WS calls. * * @param surveyId Survey ID. * @return Cache key. */ protected getQuestionsCacheKey(surveyId: number): string { return ROOT_CACHE_KEY + 'questions:' + surveyId; } /** * Get cache key for survey data WS calls. * * @param courseId Course ID. * @return Cache key. */ protected getSurveyCacheKey(courseId: number): string { return ROOT_CACHE_KEY + 'survey:' + courseId; } /** * Get a survey data. * * @param courseId Course ID. * @param key Name of the property to check. * @param value Value to search. * @param options Other options. * @return Promise resolved when the survey is retrieved. */ protected async getSurveyDataByKey( courseId: number, key: string, value: number, options: CoreSitesCommonWSOptions = {}, ): Promise<AddonModSurveySurvey> { const site = await CoreSites.getSite(options.siteId); const params: AddonModSurveyGetSurveysByCoursesWSParams = { courseids: [courseId], }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getSurveyCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModSurveyProvider.COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read<AddonModSurveyGetSurveysByCoursesWSResponse>('mod_survey_get_surveys_by_courses', params, preSets); const currentSurvey = response.surveys.find((survey) => survey[key] == value); if (currentSurvey) { return currentSurvey; } throw new CoreError('Activity not found.'); } /** * Get a survey by course module ID. * * @param courseId Course ID. * @param cmId Course module ID. * @param options Other options. * @return Promise resolved when the survey is retrieved. */ getSurvey(courseId: number, cmId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModSurveySurvey> { return this.getSurveyDataByKey(courseId, 'coursemodule', cmId, options); } /** * Get a survey by ID. * * @param courseId Course ID. * @param id Survey ID. * @param options Other options. * @return Promise resolved when the survey is retrieved. */ getSurveyById(courseId: number, id: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModSurveySurvey> { return this.getSurveyDataByKey(courseId, 'id', id, options); } /** * Invalidate the prefetched content. * * @param moduleId The module ID. * @param courseId Course ID of the module. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateContent(moduleId: number, courseId: number, siteId?: string): Promise<void> { siteId = siteId || CoreSites.getCurrentSiteId(); const promises: Promise<void>[] = []; promises.push(this.getSurvey(courseId, moduleId).then(async (survey) => { const ps: Promise<void>[] = []; // Do not invalidate activity data before getting activity info, we need it! ps.push(this.invalidateSurveyData(courseId, siteId)); ps.push(this.invalidateQuestions(survey.id, siteId)); await Promise.all(ps); return; })); promises.push(CoreFilepool.invalidateFilesByComponent(siteId, AddonModSurveyProvider.COMPONENT, moduleId)); await CoreUtils.allPromises(promises); } /** * Invalidates survey questions. * * @param surveyId Survey ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateQuestions(surveyId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getQuestionsCacheKey(surveyId)); } /** * Invalidates survey data. * * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateSurveyData(courseId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getSurveyCacheKey(courseId)); } /** * Report the survey as being viewed. * * @param id Module ID. * @param name Name of the assign. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the WS call is successful. */ async logView(id: number, name?: string, siteId?: string): Promise<void> { const params: AddonModSurveyViewSurveyWSParams = { surveyid: id, }; await CoreCourseLogHelper.logSingle( 'mod_survey_view_survey', params, AddonModSurveyProvider.COMPONENT, id, name, 'survey', {}, siteId, ); } /** * Send survey answers. If cannot send them to Moodle, they'll be stored in offline to be sent later. * * @param surveyId Survey ID. * @param name Survey name. * @param courseId Course ID the survey belongs to. * @param answers Answers. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean if success: true if answers were sent to server, * false if stored in device. */ async submitAnswers( surveyId: number, name: string, courseId: number, answers: AddonModSurveySubmitAnswerData[], siteId?: string, ): Promise<boolean> { // Convenience function to store a survey to be synchronized later. const storeOffline = async (): Promise<boolean> => { await AddonModSurveyOffline.saveAnswers(surveyId, name, courseId, answers, siteId); return false; }; siteId = siteId || CoreSites.getCurrentSiteId(); if (!CoreApp.isOnline()) { // App is offline, store the message. return storeOffline(); } try { // If there's already answers to be sent to the server, discard it first. await AddonModSurveyOffline.deleteSurveyAnswers(surveyId, siteId); // Device is online, try to send them to server. await this.submitAnswersOnline(surveyId, answers, siteId); return true; } catch (error) { if (CoreUtils.isWebServiceError(error)) { // It's a WebService error, the user cannot send the message so don't store it. throw error; } return storeOffline(); } } /** * Send survey answers to Moodle. * * @param surveyId Survey ID. * @param answers Answers. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when answers are successfully submitted. */ async submitAnswersOnline(surveyId: number, answers: AddonModSurveySubmitAnswerData[], siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); const params: AddonModSurveySubmitAnswersWSParams = { surveyid: surveyId, answers: answers, }; const response = await site.write<CoreStatusWithWarningsWSResponse>('mod_survey_submit_answers', params); if (!response.status) { throw new CoreError('Error submitting answers.'); } } } export const AddonModSurvey = makeSingleton(AddonModSurveyProvider); /** * Params of mod_survey_view_survey WS. */ type AddonModSurveyViewSurveyWSParams = { surveyid: number; // Survey instance id. }; /** * Survey returned by WS mod_survey_get_surveys_by_courses. */ export type AddonModSurveySurvey = { id: number; // Survey id. coursemodule: number; // Course module id. course: number; // Course id. name: string; // Survey name. intro?: string; // The Survey intro. introformat?: number; // Intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). introfiles?: CoreWSExternalFile[]; // @since 3.2. template?: number; // Survey type. days?: number; // Days. questions?: string; // Question ids. surveydone?: number; // Did I finish the survey?. timecreated?: number; // Time of creation. timemodified?: number; // Time of last modification. section?: number; // Course section id. visible?: number; // Visible. groupmode?: number; // Group mode. groupingid?: number; // Group id. }; /** * Survey question. */ export type AddonModSurveyQuestion = { id: number; // Question id. text: string; // Question text. shorttext: string; // Question short text. multi: string; // Subquestions ids. intro: string; // The question intro. type: number; // Question type. options: string; // Question options. parent: number; // Parent question (for subquestions). }; /** * Params of mod_survey_get_questions WS. */ type AddonModSurveyGetQuestionsWSParams = { surveyid: number; // Survey instance id. }; /** * Data returned by mod_survey_get_questions WS. */ export type AddonModSurveyGetQuestionsWSResponse = { questions: AddonModSurveyQuestion[]; warnings?: CoreWSExternalWarning[]; }; /** * Params of mod_survey_get_surveys_by_courses WS. */ type AddonModSurveyGetSurveysByCoursesWSParams = { courseids?: number[]; // Array of course ids. }; /** * Data returned by mod_survey_get_surveys_by_courses WS. */ export type AddonModSurveyGetSurveysByCoursesWSResponse = { surveys: AddonModSurveySurvey[]; warnings?: CoreWSExternalWarning[]; }; export type AddonModSurveySubmitAnswerData = { key: string; // Answer key. value: string; // Answer value. }; /** * Params of mod_survey_submit_answers WS. */ type AddonModSurveySubmitAnswersWSParams = { surveyid: number; // Survey id. answers: AddonModSurveySubmitAnswerData[]; };
the_stack
import { Aws, CfnResource, Construct, Duration, Stack, Tags } from '@aws-cdk/core'; import { Code, Function as LambdaFunction, Runtime } from '@aws-cdk/aws-lambda'; import { Effect, PolicyStatement, PolicyDocument, Role, ServicePrincipal, Policy } from '@aws-cdk/aws-iam'; import { IBucket } from '@aws-cdk/aws-s3'; import { Table } from '@aws-cdk/aws-dynamodb'; import { LogGroup } from '@aws-cdk/aws-logs'; /** * TestRunnerLambdasConstruct props * @interface TestRunnerLambdaConstructProps */ export interface TestRunnerLambdasContructProps { readonly cloudWatchLogsPolicy: Policy; // DynamoDB policy readonly dynamoDbPolicy: Policy; //ECS Task Execution Role ARN readonly ecsTaskExecutionRoleArn: string; // ECS CloudWatch LogGroup ; readonly ecsCloudWatchLogGroup: LogGroup; // ECS Cluster readonly ecsCluster: string; // ECS Task definition readonly ecsTaskDefinition: string; // ECS Security Group readonly ecsTaskSecurityGroup: string; // Scenarios S3 Bucket policy readonly scenariosS3Policy: Policy; // Subnet A Id readonly subnetA: string; // Subnet B Id readonly subnetB: string /** * Solution config properties. * the metric URL endpoint, send anonymous usage, solution ID, version, source code bucket, and source code prefix */ readonly metricsUrl: string; readonly sendAnonymousUsage: string; readonly solutionId: string; readonly solutionVersion: string; readonly sourceCodeBucket: IBucket; readonly sourceCodePrefix: string; // Test scenarios bucket readonly testScenariosBucket: string; // Test scenarios table readonly testScenariosTable: Table; // Stack UUID readonly uuid: string; } /** * @class * Distributed Load Testing on AWS Test Runner Lambdas construct. * This creates the Results parser, Task Runner, Task Canceler, * and Task Status Checker */ export class TestRunnerLambdasConstruct extends Construct { public resultsParser: LambdaFunction; public taskRunner: LambdaFunction; public taskCanceler: LambdaFunction; public taskCancelerInvokePolicy: Policy; public taskStatusChecker: LambdaFunction; constructor(scope: Construct, id: string, props: TestRunnerLambdasContructProps) { super(scope, id); const lambdaResultsRole = new Role(this, 'LambdaResultsRole', { assumedBy: new ServicePrincipal('lambda.amazonaws.com') }); const cfnPolicy = new Policy(this, 'LambdaResultsPolicy', { statements: [ new PolicyStatement({ resources: ['*'], actions: ['cloudwatch:GetMetricWidgetImage'] }) ] }); lambdaResultsRole.attachInlinePolicy(cfnPolicy); lambdaResultsRole.attachInlinePolicy(props.cloudWatchLogsPolicy); lambdaResultsRole.attachInlinePolicy(props.dynamoDbPolicy); lambdaResultsRole.attachInlinePolicy(props.scenariosS3Policy); const resultsRoleResource = lambdaResultsRole.node.defaultChild as CfnResource; resultsRoleResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W12', reason: 'The action does not support resource level permissions.' }] }); const resultsPolicyResource = cfnPolicy.node.defaultChild as CfnResource; resultsPolicyResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W12', reason: 'The action does not support resource level permissions.' }] }); this.resultsParser = new LambdaFunction(this, 'ResultsParser', { description: 'Result parser for indexing xml test results to DynamoDB', handler: 'index.handler', role: lambdaResultsRole, code: Code.fromBucket(props.sourceCodeBucket, `${props.sourceCodePrefix}/results-parser.zip`), runtime: Runtime.NODEJS_14_X, timeout: Duration.seconds(120), environment: { SCENARIOS_BUCKET: props.testScenariosBucket, SCENARIOS_TABLE: props.testScenariosTable.tableName, SOLUTION_ID: props.solutionId, UUID: props.uuid, VERSION: props.solutionVersion, SEND_METRIC: props.sendAnonymousUsage, METRIC_URL: props.metricsUrl }, }); Tags.of(this.resultsParser).add('SolutionId', props.solutionId); const resultsParserResource = this.resultsParser.node.defaultChild as CfnResource; resultsParserResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W58', reason: 'CloudWatchLogsPolicy covers a permission to write CloudWatch logs.' }, { id: 'W89', reason: 'This Lambda function does not require a VPC' }, { id: 'W92', reason: 'Does not run concurrent executions' },] }); const taskArn = Stack.of(this).formatArn({ service: 'ecs', resource: 'task', sep: '/', resourceName: '*' }); const taskDefArn = Stack.of(this).formatArn({ service: 'ecs', resource: 'task-definition', resourceName: '*:*' }); const lambdaTaskRole = new Role(this, 'DLTTestLambdaTaskRole', { assumedBy: new ServicePrincipal('lambda.amazonaws.com'), inlinePolicies: { 'TaskLambdaPolicy': new PolicyDocument({ statements: [ new PolicyStatement({ effect: Effect.ALLOW, actions: ['ecs:ListTasks'], resources: ['*'] }), new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'ecs:RunTask', 'ecs:DescribeTasks' ], resources: [ taskArn, taskDefArn ] }), new PolicyStatement({ effect: Effect.ALLOW, actions: ['iam:PassRole'], resources: [props.ecsTaskExecutionRoleArn] }), new PolicyStatement({ effect: Effect.ALLOW, actions: ['logs:PutMetricFilter'], resources: [props.ecsCloudWatchLogGroup.logGroupArn] }), new PolicyStatement({ effect: Effect.ALLOW, actions: ['cloudwatch:PutDashboard'], resources: [ `arn:${Aws.PARTITION}:cloudwatch::${Aws.ACCOUNT_ID}:dashboard/EcsLoadTesting*` ] }) ] }) } }); lambdaTaskRole.attachInlinePolicy(props.cloudWatchLogsPolicy); lambdaTaskRole.attachInlinePolicy(props.dynamoDbPolicy); const lambdaTaskRoleResource = lambdaTaskRole.node.defaultChild as CfnResource; lambdaTaskRoleResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W11', reason: 'ecs:ListTasks does not support resource level permissions' }] }); this.taskRunner = new LambdaFunction(this, 'TaskRunner', { description: 'Task runner for ECS task definitions', handler: 'index.handler', role: lambdaTaskRole, code: Code.fromBucket(props.sourceCodeBucket, `${props.sourceCodePrefix}/task-runner.zip`), environment: { SCENARIOS_BUCKET: props.testScenariosBucket, SCENARIOS_TABLE: props.testScenariosTable.tableName, TASK_CLUSTER: props.ecsCluster, TASK_DEFINITION: props.ecsTaskDefinition, TASK_SECURITY_GROUP: props.ecsTaskSecurityGroup, TASK_IMAGE: `${Aws.STACK_NAME}-load-tester`, SUBNET_A: props.subnetA, SUBNET_B: props.subnetB, API_INTERVAL: '10', ECS_LOG_GROUP: props.ecsCloudWatchLogGroup.logGroupName, SOLUTION_ID: props.solutionId, VERSION: props.solutionVersion }, runtime: Runtime.NODEJS_14_X, timeout: Duration.seconds(900) }); Tags.of(this.taskRunner).add('SolutionId', props.solutionId); const taskRunnerResource = this.taskRunner.node.defaultChild as CfnResource; taskRunnerResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W58', reason: 'CloudWatchLogsPolicy covers a permission to write CloudWatch logs.' }, { id: 'W89', reason: 'This Lambda function does not require a VPC' }, { id: 'W92', reason: 'Does not run concurrent executions' }] }); const taskCancelerRole = new Role(this, 'LambdaTaskCancelerRole', { assumedBy: new ServicePrincipal('lambda.amazonaws.com'), inlinePolicies: { 'TaskCancelerPolicy': new PolicyDocument({ statements: [ new PolicyStatement({ effect: Effect.ALLOW, actions: ['ecs:ListTasks'], resources: ['*'] }), new PolicyStatement({ effect: Effect.ALLOW, actions: ['ecs:StopTask'], resources: [ taskArn, taskDefArn ] }), new PolicyStatement({ effect: Effect.ALLOW, actions: ['dynamodb:UpdateItem'], resources: [props.testScenariosTable.tableArn] }) ] }) } }); taskCancelerRole.attachInlinePolicy(props.cloudWatchLogsPolicy); const taskCancelerRoleResource = taskCancelerRole.node.defaultChild as CfnResource; taskCancelerRoleResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W11', reason: 'ecs:ListTasks does not support resource level permissions' }] }); this.taskCanceler = new LambdaFunction(this, 'TaskCanceler', { description: 'Stops ECS task', handler: 'index.handler', role: taskCancelerRole, code: Code.fromBucket(props.sourceCodeBucket, `${props.sourceCodePrefix}/task-canceler.zip`), runtime: Runtime.NODEJS_14_X, timeout: Duration.seconds(300), environment: { METRIC_URL: props.metricsUrl, SOLUTION_ID: props.solutionId, VERSION: props.solutionVersion, SCENARIOS_TABLE: props.testScenariosTable.tableName, TASK_CLUSTER: props.ecsCluster } }); Tags.of(this.taskCanceler).add('SolutionId', props.solutionId); const taskCancelerResource = this.taskCanceler.node.defaultChild as CfnResource; taskCancelerResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W58', reason: 'CloudWatchLogsPolicy covers a permission to write CloudWatch logs.' }, { id: 'W89', reason: 'This Lambda function does not require a VPC' }, { id: 'W92', reason: 'Does not run concurrent executions' }] }); this.taskCancelerInvokePolicy = new Policy(this, 'TaskCancelerInvokePolicy', { statements: [ new PolicyStatement({ effect: Effect.ALLOW, actions: ['lambda:InvokeFunction'], resources: [this.taskCanceler.functionArn] }) ] }) const taskStatusCheckerRole = new Role(this, 'TaskStatusRole', { assumedBy: new ServicePrincipal('lambda.amazonaws.com'), inlinePolicies: { 'TaskStatusPolicy': new PolicyDocument({ statements: [ new PolicyStatement({ effect: Effect.ALLOW, actions: ['ecs:ListTasks'], resources: ['*'] }), new PolicyStatement({ effect: Effect.ALLOW, actions: ['ecs:DescribeTasks'], resources: [ taskArn ] }) ] }) } }); taskStatusCheckerRole.attachInlinePolicy(props.cloudWatchLogsPolicy); taskStatusCheckerRole.attachInlinePolicy(this.taskCancelerInvokePolicy); taskStatusCheckerRole.attachInlinePolicy(props.dynamoDbPolicy); const taskStatusCheckerRoleResource = taskStatusCheckerRole.node.defaultChild as CfnResource; taskStatusCheckerRoleResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W11', reason: 'ecs:ListTasks does not support resource level permissions' }, { id: 'W58', reason: 'CloudWatchLogsPolicy covers a permission to write CloudWatch logs.' }] }); this.taskStatusChecker = new LambdaFunction(this, 'TaskStatusChecker', { description: 'Task status checker', handler: 'index.handler', role: taskStatusCheckerRole, code: Code.fromBucket(props.sourceCodeBucket, `${props.sourceCodePrefix}/task-status-checker.zip`), runtime: Runtime.NODEJS_14_X, timeout: Duration.seconds(180), environment: { TASK_CLUSTER: props.ecsCluster, SCENARIOS_TABLE: props.testScenariosTable.tableName, TASK_CANCELER_ARN: this.taskCanceler.functionArn, SOLUTION_ID: props.solutionId, VERSION: props.solutionVersion } }); Tags.of(this.taskStatusChecker).add('SolutionId', props.solutionId); const taskStatusCheckerResource = this.taskStatusChecker.node.defaultChild as CfnResource; taskStatusCheckerResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W58', reason: 'CloudWatchLogsPolicy covers a permission to write CloudWatch logs.' }, { id: 'W89', reason: 'This Lambda function does not require a VPC' }, { id: 'W92', reason: 'Does not run concurrent executions' },] }); } }
the_stack
export type FetchResult = { /** * Offset the opcode was read from */ offset: number; /** * Overflow detected? */ overflow: boolean; /** * Opcode fetched */ opcode: number; } /** * This class represents the output of a single disassembly item */ export interface DisassemblyItem { /** * The memory address of the disassembled instruction */ address: number; /** * Operation codes used for the disassembly */ opCodes?: string; /** * Indicates that the disassembly instruction has an associated label */ hasLabel?: boolean; /** * The Z80 assembly instruction */ instruction?: string; /** * Disassembler-generated comment */ hardComment?: string; /** * The start position of token to replace */ tokenPosition?: number; /** * The length of token to replace */ tokenLength?: number; /** * Signs that this item has a symbol that can be associated with a literal */ hasSymbol?: boolean; /** * The symbol value */ symbolValue?: number; /** * Indicates if this item has a label symbol */ hasLabelSymbol?: boolean; /** * Formatted label */ formattedLabel?: string; /** * Formatted comment */ formattedComment?: string; /** * Signs that this item is just a prefix item */ isPrefixItem?: boolean; /** * The optional prefix comment */ prefixComment?: string; } /** * This class represents the output of the disassembly project */ export class DisassemblyOutput { private _outputItems = new Array<DisassemblyItem>(); private _outputByAddress = new Map<number, DisassemblyItem>(); private readonly _labels = new Map<number, DisassemblyLabel>(); /** * Gets the list of output items */ get outputItems(): Array<DisassemblyItem> { return this._outputItems; } /** * Gets the labels created during disassembly */ get labels(): Map<number, DisassemblyLabel> { return this._labels; } /** * Clears the entire output */ clear(): void { this._outputItems = new Array<DisassemblyItem>(); this._outputByAddress = new Map<number, DisassemblyItem>(); } /** * Adds a new item to the output * @param item Disassembly item to add */ addItem(item: DisassemblyItem): void { this._outputItems.push(item); this._outputByAddress.set(item.address, item); } /** * Gets a disassembly item by its address * @param addr Item address * @returns The speicifid item, if found; otherwise, undefined */ get(addr: number): DisassemblyItem | undefined { return this._outputByAddress.get(addr); } /** * Creates a new label according to its address and optional name * @param addr Label address * @param referringOpAddr The address of operation referring to the label * @returns The newly created label */ createLabel(addr: number, referringOpAddr?: number): void { let label = this._labels.get(addr); if (!label) { label = new DisassemblyLabel(addr); this._labels.set(label.address, label); } if (referringOpAddr) { label.references.push(referringOpAddr); } } /** * Replaces the original output items * @param items Items to replace the original output with */ replaceOutputItems(items: DisassemblyItem[]): void { this._outputItems = items; this._outputByAddress.clear(); for (const item of items) { if (!item.isPrefixItem) { this._outputByAddress.set(item.address, item); } } } } /** * This class describes a label with its references */ export class DisassemblyLabel { /** * Label address */ address: number; /** * Addresses of instructions that reference this label */ readonly references: Array<number>; /** * Initializes disassembly label information * @param address Label address */ constructor(address: number) { this.address = address; this.references = new Array<number>(); } } /** * This enumeration represents the memory section types that can be used * when disassemblying a project. */ export enum MemorySectionType { /** * Simply skip the section without any output code generation */ Skip, /** * Create Z80 disassembly for the memory section */ Disassemble, /** * Create a byte array for the memory section */ ByteArray, /** * Create a word array for the memory section */ WordArray, /** * Create an RST 28 bytecode memory section */ CustomSection, } /** * This class describes a memory section with a start address and a length */ export class MemorySection { private _start = 0; private _end = 0; private _type = MemorySectionType.Disassemble; private _custom: string | null = null; /** * The start address of the section */ get startAddress() { return this._start; } set startAddress(value: number) { this._start = value & 0xffff; } /** * The end address of the section (inclusive) */ get endAddress() { return this._end; } set endAddress(value: number) { this._end = value & 0xffff; } /** * The type of the memory section */ get sectionType() { return this._type; } set sectionType(value: MemorySectionType) { this._type = value; } /** * Gets the subtype of a custom section */ get customType(): string | null { return this._custom; } /** * The lenght of the memory section */ get lenght(): number { return (this.endAddress - this.startAddress + 1) & 0xffff; } /** * Creates a MemorySection with the specified properties * @param startAddress Starting address * @param endAddress Ending address (inclusive) * @param sectionType Section type */ constructor( startAddress: number, endAddress: number, sectionType = MemorySectionType.Disassemble ) { if (endAddress >= startAddress) { this.startAddress = startAddress; this.endAddress = endAddress; } else { this.startAddress = endAddress; this.endAddress = startAddress; } this.sectionType = sectionType; } /** * Checks if this memory section overlaps with the othe one * @param other Other memory section * @return True, if the sections overlap */ overlaps(other: MemorySection): boolean { return ( (other._start >= this._start && other._start <= this._end) || (other._end >= this._start && other._end <= this._end) || (this._start >= other._start && this._start <= other._end) || (this._end >= other._start && this._end <= other._end) ); } /** * Checks if this section has the same start and length than the other * @param other Other memory section * @return True, if the sections have the same start and length */ sameSection(other: MemorySection): boolean { return this._start === other._start && this._end === other._end; } /** * Gets the intersection of the two memory sections * @param other Other memory section * @return Intersection, if exists; otherwise, undefined */ intersect(other: MemorySection): MemorySection | undefined { let intStart = -1; let intEnd = -1; if (other._start >= this._start && other._start <= this._end) { intStart = other._start; } if (other._end >= this._start && other._end <= this._end) { intEnd = other._end; } if (this._start >= other._start && this._start <= other._end) { intStart = this._start; } if (this._end >= other._start && this._end <= other._end) { intEnd = this._end; } return intStart < 0 || intEnd < 0 ? undefined : new MemorySection(intStart, intEnd); } /** * * @param other Checks if this memory section equals with the other */ equals(other: MemorySection): boolean { return ( this._start === other._start && this._end === other._end && this._type === other._type ); } } /** * This class implements a memory map of a Z80 virtual machine. * Internally, the sections of the memory map are kept ordered by the section's * start addresses. */ export class MemoryMap { sections: MemorySection[] = []; /** * Gets the count of items in the memory map */ get count() { return this.sections.length; } /** * Adds the specified item to the map * @param item Memory section item to add to the map */ add(item: MemorySection): void { // --- We store the items of the list in ascending order by StartAddress let overlapFound: boolean; do { overlapFound = false; // --- Adjust all old sections that overlap with the new one for (let i = 0; i < this.sections.length; i++) { var oldSection = this.sections[i]; if (item.overlaps(oldSection)) { // --- The new item overlaps with one of the exisitning ones overlapFound = true; const oldStart = oldSection.startAddress; const oldEndEx = oldSection.endAddress; const newStart = item.startAddress; const newEndEx = item.endAddress; if (oldStart < newStart) { // --- Adjust the length of the old section: // --- it gets shorter oldSection.endAddress = newStart - 1; if (oldEndEx > newEndEx) { // --- The rightmost part of the old section becomes a new section const newSection = new MemorySection(newEndEx + 1, oldEndEx); this.sections.splice(i + 1, 0, newSection); } break; } if (oldStart >= newStart) { if (oldEndEx <= newEndEx) { // --- The old section entirely intersects wiht the new section: // --- Remove the old section this.sections.splice(i, 1); } else { // --- Change the old sections's start address oldSection.startAddress = newEndEx + 1; } break; } } } } while (overlapFound); // --- At this point we do not have no old overlapping section anymore. // --- Insert the nex section to its place according to its StartAddress let insertPos = this.sections.length; for (var i = 0; i < this.sections.length; i++) { if (this.sections[i].startAddress > item.startAddress) { // --- This is the right place to insert the new section insertPos = i; break; } } this.sections.splice(insertPos, 0, item); } /** * Merges the sections of another map into this one * @param map Map to merge into this one * @param offset Optional offset of start and end addresses */ merge(map: MemoryMap, offset: number = 0): void { if (!map) { return; } for (const section of map.sections) { this.add( new MemorySection( section.startAddress + offset, section.endAddress + offset, section.sectionType ) ); } } /** * Joins adjacent Disassembly memory sections */ normalize(): void { var changed = true; while (changed) { changed = false; for (var i = 1; i < this.count; i++) { const prevSection = this.sections[i - 1]; const currentSection = this.sections[i]; if ( prevSection.endAddress !== currentSection.startAddress - 1 || prevSection.sectionType !== MemorySectionType.Disassemble || currentSection.sectionType !== MemorySectionType.Disassemble ) { continue; } prevSection.endAddress = currentSection.endAddress; this.sections.splice(i, 1); changed = true; } } } } /** * Allows the JavaScript event loop to process waiting messages */ export function processMessages(): Promise<void> { return new Promise<void>((resolve) => { setTimeout(() => { resolve(); }, 0); }); } /** * Converts an unsigned byte to a signed byte */ export function toSbyte(x: number) { x &= 0xff; return x >= 128 ? x - 256 : x; } /** * Converts value to a signed short */ export function toSshort(x: number) { x &= 0xffff; return x >= 32768 ? x - 65536 : x; } /** * Converts the input value to a 2-digit hexadecimal string * @param value Value to convert */ export function intToX2(value: number): string { const hnum = value.toString(16).toUpperCase(); if (hnum.length >= 2) { return hnum; } return "0" + hnum; } /** * Converts the input value to a 4-digit hexadecimal string * @param value Value to convert */ export function intToX4(value: number): string { const hnum = value.toString(16).toUpperCase(); if (hnum.length >= 4) { return hnum; } return "0000".substring(0, 4 - hnum.length) + hnum; }
the_stack
import { CUSTOM_ELEMENTS_SCHEMA, EventEmitter, SimpleChange, Component } from '@angular/core'; import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { MockComponent } from 'ng2-mock-component'; import { using } from 'app/testing/spec-helpers'; import { ChefPipesModule } from 'app/pipes/chef-pipes.module'; import { ResourceDropdownComponent, ResourceChecked, ResourceCheckedSection } from './resource-dropdown.component'; const testResources = [genResourceList( genResource('name1', true), genResource('name2', false), genResource('name3', true), genResource('name4', true), genResource('name5', false) )]; @Component({ template: `<app-resource-dropdown [resources]="resources" [resourcesUpdated]="resourcesUpdatedEvent" [objectNounPlural]="'hummingbirds'" (onDropdownClosing)="onClosing($event)"> Description here... </app-resource-dropdown>` }) class TestHostComponent { resources = testResources; resourceIDs: string[]; onClosing(resourceIDs: string[]): void { this.resourceIDs = resourceIDs; } } // This section is an example of how to get closer to the UI in unit tests. // Here we are actually clicking an HTML button rather than firing the internal ngOnChanges // as is done in later tests in this file. describe('HostedMessageModalComponent', () => { let hostComponent: TestHostComponent; let fixture: ComponentFixture<TestHostComponent>; let dropdownComponent: ResourceDropdownComponent; let dropdownElement: HTMLElement; let dropdownButton: HTMLButtonElement; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ ChefPipesModule ], declarations: [ MockComponent({ selector: 'input', inputs: ['ngModel'] }), TestHostComponent, ResourceDropdownComponent ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TestHostComponent); hostComponent = fixture.componentInstance; dropdownComponent = fixture.debugElement.children[0].componentInstance; dropdownElement = fixture.nativeElement; dropdownButton = dropdownElement.querySelector('.dropdown-button'); fixture.detectChanges(); }); it('should be created', () => { expect(hostComponent).toBeTruthy(); expect(dropdownComponent).toBeTruthy(); }); // Test the key INPUT it('passes in resource list through "resource" parameter', () => { expect(dropdownComponent.dropdownState).toEqual('closed'); expect(dropdownComponent.filteredResources).toEqual(testResources); toggleDropdown(); // open expect(dropdownComponent.dropdownState).toEqual('open'); const options: HTMLChefCheckboxElement[] = Array.from( dropdownElement.querySelectorAll('chef-checkbox')); expect(options.length).toEqual(testResources[0].itemList.length); for (let i = 0; i < options.length; i++) { const { name, checked } = testResources[0].itemList[i]; expect(options[i].textContent).toEqual(name); expect(options[i].checked).toEqual(checked); } }); // Test the key OUTPUT it('emits list of checked resources upon close', () => { expect(dropdownComponent.dropdownState).toEqual('closed'); expect(hostComponent.resourceIDs).toBeUndefined(); toggleDropdown(); // open expect(dropdownComponent.dropdownState).toEqual('open'); expect(hostComponent.resourceIDs).toBeUndefined(); // only gets set on close, so not yet... toggleDropdown(); // close expect(dropdownComponent.dropdownState).toEqual('closed'); // check what is emitted on close expect(hostComponent.resourceIDs) .toEqual(testResources[0].itemList.filter(r => r.checked).map(r => r.name)); }); // Test data persistence across opening/closing it('retains checked items after closing then re-opening dropdown', () => { expect(dropdownComponent.dropdownState).toEqual('closed'); expect(dropdownComponent.filteredResources).toEqual(testResources); expect(dropdownComponent.label).toEqual('3 hummingbirds'); toggleDropdown(); // open expect(dropdownComponent.dropdownState).toEqual('open'); // now add one more checked item dropdownComponent.resourceChecked(true, dropdownComponent.filteredResources[0].itemList[1]); expect(dropdownComponent.label).toEqual('4 hummingbirds'); toggleDropdown(); // close expect(dropdownComponent.dropdownState).toEqual('closed'); toggleDropdown(); // re-open expect(dropdownComponent.dropdownState).toEqual('open'); expect(dropdownComponent.label).toEqual('4 hummingbirds'); }); function toggleDropdown(): void { dropdownButton.click(); dropdownComponent.handleClickOutside(); // in the browser, this fires automatically after click } }); describe('ResourceDropdownComponent', () => { let component: ResourceDropdownComponent; let fixture: ComponentFixture<ResourceDropdownComponent>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ResourceDropdownComponent], imports: [ChefPipesModule, FormsModule], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ResourceDropdownComponent); component = fixture.componentInstance; component.resourcesUpdated = new EventEmitter(); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('displays a list of checkbox options', () => { component.filteredResources = [ genResourceList( genResource('project 1', false), genResource('project 2', true), genResource('project 3', true) ) ]; fixture.detectChanges(); const options: HTMLInputElement[] = Array.from(fixture.nativeElement.querySelectorAll('chef-checkbox')); expect(options.length).toEqual(component.filteredResources[0].itemList.length); options.forEach((option, index) => { const { name, checked } = component.filteredResources[0].itemList[index]; expect(option.textContent).toEqual(name); expect(option.checked).toEqual(checked); }); }); it('renders resources WITHOUT sorting ', () => { // thus allowing custom ordering const resources = [genResourceList( genResource('zz', false), genResource('cc', true), genResource('aa', false), genResource('bb', true) )]; component.objectNounPlural = 'policies'; toggleDropdown(); // open changeResources([], resources, true); expect(component.filteredResources[0].itemList.map(r => r.name)) .toEqual(['zz', 'cc', 'aa', 'bb']); }); describe('user scenarios', () => { const resources = [genResourceList( // 3 checked items genResource('name1', true), genResource('name2', false), genResource('other_name3', true), genResource('name4', true), genResource('other_name5', false) )]; const resourcesNew = [genResourceList( // 2 checked items genResource('name1', true), genResource('name4', true), genResource('other_name5', false) )]; it('retains checked items after closing then re-opening dropdown', () => { specifyLemursAndOpenDropdown(); // make a change component.resourceChecked(true, component.filteredResources[0].itemList[1]); expect(component.label).toEqual('4 lemurs'); toggleDropdown(); // close expect(component.dropdownState).toEqual('closed'); toggleDropdown(); // ... and reopen expect(component.dropdownState).toEqual('open'); expect(component.label).toEqual('4 lemurs'); }); it('retains checked items after closing, updating resources, then re-opening dropdown', () => { specifyLemursAndOpenDropdown(); // make a change component.resourceChecked(true, component.filteredResources[0].itemList[1]); expect(component.label).toEqual('4 lemurs'); toggleDropdown(); // close expect(component.dropdownState).toEqual('closed'); changeResources(resources, resourcesNew, false); // <----------Update resources toggleDropdown(); // ... and reopen expect(component.dropdownState).toEqual('open'); expect(component.label).toEqual('4 lemurs'); }); it('clears checked items after force resetting', () => { specifyLemursAndOpenDropdown(); // make a change component.resourceChecked(true, component.filteredResources[0].itemList[1]); expect(component.label).toEqual('4 lemurs'); toggleDropdown(); // close expect(component.dropdownState).toEqual('closed'); component.resourcesUpdated.emit(true); // force update here toggleDropdown(); // ... and reopen expect(component.dropdownState).toEqual('open'); expect(component.label).toEqual('3 lemurs'); }); it('clears checked items after updating resources then force resetting', () => { specifyLemursAndOpenDropdown(); // make a change component.resourceChecked(true, component.filteredResources[0].itemList[1]); expect(component.label).toEqual('4 lemurs'); toggleDropdown(); // close expect(component.dropdownState).toEqual('closed'); changeResources(resources, resourcesNew, false); // <----------Update resources component.resourcesUpdated.emit(true); // force update here toggleDropdown(); // ... and reopen expect(component.dropdownState).toEqual('open'); expect(component.label).toEqual('2 lemurs'); }); it('applies filter but leaves label unchanged', () => { specifyLemursAndOpenDropdown(); // make a change component.resourceChecked(true, component.filteredResources[0].itemList[1]); expect(component.label).toEqual('4 lemurs'); // apply filter component.filterValue = 'other'; component.handleFilterKeyUp(); expect(component.label).toEqual('4 lemurs'); expect(component.filteredResources[0].itemList[0].name).toEqual('other_name3'); expect(component.filteredResources[0].itemList[0].checked).toEqual(true); expect(component.filteredResources[0].itemList[1].name).toEqual('other_name5'); expect(component.filteredResources[0].itemList[1].checked).toEqual(false); }); it('applies filter and updates resources but leaves label unchanged', () => { specifyLemursAndOpenDropdown(); // make a change component.resourceChecked(true, component.filteredResources[0].itemList[1]); expect(component.label).toEqual('4 lemurs'); // apply filter component.filterValue = 'other'; component.handleFilterKeyUp(); changeResources(resources, resourcesNew, false); // <----------Update resources expect(component.label).toEqual('4 lemurs'); expect(component.filteredResources[0].itemList[0].name).toEqual('other_name3'); expect(component.filteredResources[0].itemList[0].checked).toEqual(true); expect(component.filteredResources[0].itemList[1].name).toEqual('other_name5'); expect(component.filteredResources[0].itemList[1].checked).toEqual(false); }); it('retains checked items after filter applied', () => { specifyLemursAndOpenDropdown(); // make a change const target = component.filteredResources[0].itemList[1]; expect(target.checked).toEqual(false); component.resourceChecked(true, component.filteredResources[0].itemList[1]); expect(component.label).toEqual('4 lemurs'); expect(target.checked).toEqual(true); // apply filter component.filterValue = 'other'; component.handleFilterKeyUp(); expect(component.label).toEqual('4 lemurs'); expect(target.checked).toEqual(true); // clear filter component.filterValue = ''; component.handleFilterKeyUp(); expect(component.label).toEqual('4 lemurs'); expect(target.checked).toEqual(true); }); it('retains checked items after filter applied and resources updated', () => { specifyLemursAndOpenDropdown(); // make a change const target = component.filteredResources[0].itemList[1]; expect(target.checked).toEqual(false); component.resourceChecked(true, component.filteredResources[0].itemList[1]); expect(component.label).toEqual('4 lemurs'); expect(target.checked).toEqual(true); // apply filter component.filterValue = 'other'; component.handleFilterKeyUp(); expect(component.label).toEqual('4 lemurs'); expect(target.checked).toEqual(true); changeResources(resources, resourcesNew, false); // <----------Update resources // clear filter component.filterValue = ''; component.handleFilterKeyUp(); expect(component.label).toEqual('4 lemurs'); expect(target.checked).toEqual(true); }); it('clears filter upon re-opening', () => { specifyLemursAndOpenDropdown(); // make a change component.resourceChecked(true, component.filteredResources[0].itemList[1]); expect(component.label).toEqual('4 lemurs'); // apply filter component.filterValue = 'other'; component.handleFilterKeyUp(); expect(component.label).toEqual('4 lemurs'); expect(component.filteredResources[0].itemList.length).toEqual(2); toggleDropdown(); // close expect(component.dropdownState).toEqual('closed'); toggleDropdown(); // re-open expect(component.filteredResources[0].itemList.length).toEqual(5); }); function specifyLemursAndOpenDropdown() { expect(component.dropdownState).toEqual('closed'); component.objectNounPlural = 'lemurs'; changeResources([], resources, true); toggleDropdown(); expect(component.filteredResources).toEqual(resources); expect(component.label).toEqual('3 lemurs'); expect(component.dropdownState).toEqual('open'); } }); describe('label', () => { it('allows customizing "none" designator', () => { component.noneSelectedLabel = 'zilch'; changeResources([], [], true); expect(component.label).toEqual('zilch'); }); using([ ['single unchecked resource', [genResourceList( genResource('name1', false) )]], ['two resources but none checked', [genResourceList( genResource('name1', false), genResource('name2', false) )]] ], function (description: string, resources: ResourceCheckedSection[]) { it(`displays 'none' designator for ${description}`, () => { changeResources([], resources, true); expect(component.label).toEqual('None'); }); }); using([ ['single checked resource', [genResourceList( genResource('target resource', true) )]], ['two resources but just one checked', [genResourceList( genResource('other resource2', false), genResource('target resource', true) )]], ['multiple resources but just one checked in the middle', [genResourceList( genResource('other resource1', false), genResource('other resource2', false), genResource('target resource', true), genResource('other resource3', false) )]], ['multiple resources but just one checked at the top', [genResourceList( genResource('target resource', true), genResource('other resource1', false), genResource('other resource2', false), genResource('other resource3', false), genResource('other resource4', false) )]], ['multiple resources but just one checked at the bottom', [genResourceList( genResource('other resource1', false), genResource('other resource2', false), genResource('target resource', true) )]] ], function (description: string, resources: ResourceCheckedSection[]) { it(`displays resource name for ${description}`, () => { changeResources([], resources, true); expect(component.label).toEqual('target resource'); }); }); using([ ['some checked and some not checked', 3, [genResourceList( genResource('name1', true), genResource('name2', false), genResource('name3', true), genResource('name4', true), genResource('name5', false) )]], ['all checked', 4, [genResourceList( genResource('name1', true), genResource('name2', true), genResource('name3', true), genResource('name4', true) )]], ['just two and both checked', 2, [genResourceList( genResource('name1', true), genResource('name2', true) )]] ], function (description: string, count: number, resources: ResourceCheckedSection[]) { it(`displays resource designator with count for multiple resources with ${description}`, () => { component.objectNounPlural = 'lemurs'; changeResources([], resources, true); expect(component.label).toEqual(`${count} lemurs`); }); }); }); function toggleDropdown() { // The event from an actual click on the dropdown fires *both* of these in the order given. component.toggleDropdown(); component.handleClickOutside(); } function changeResources( original: ResourceCheckedSection[], changed: ResourceCheckedSection[], firstChange) { // Programmatic change to an @Input does *not* trigger ngOnChanges like in the actual view, // so have to do that explicitly component.resources = changed; component.ngOnChanges({ resources: new SimpleChange(original, changed, firstChange) }); } }); function genResourceList(...resources: ResourceChecked[]): ResourceCheckedSection { // Though title is technically optional, we need to supply it here so we can compare // filteredResources to resources in one step in specifyLemursAndOpenDropdown(). return { title: 'any', itemList: resources }; } function genResource(name: string, checked: boolean): ResourceChecked { return { id: name.replace(' ', '-'), name, checked }; }
the_stack
import AbstractSyntaxContent from "./AbstractSyntaxContent"; import LibProvider from "../libProvider"; const libProvider = new LibProvider(); export default class SyntaxContentOscript extends AbstractSyntaxContent { public getSyntaxContentItems(): any { const items = {}; const structureGlobContext = libProvider.oscriptStdLib.structureMenu; const globalfunctions = libProvider.oscriptStdLib.globalfunctions; const classesOscript = libProvider.oscriptStdLib.classes; const systemEnum = libProvider.oscriptStdLib.systemEnum; for (const element in structureGlobContext.global) { const segment = structureGlobContext.global[element]; const segmentChar = {}; for (const key in segment) { let signature1C; let description1C; let returns1C; if (globalfunctions[key]) { // tslint:disable-next-line:no-string-literal if (!segmentChar["methods"]) { // tslint:disable-next-line:no-string-literal segmentChar["methods"] = {}; } const methodData = globalfunctions[key]; if (libProvider.bslglobals.globalfunctions[key]) { signature1C = libProvider.bslglobals.globalfunctions[key].signature; description1C = libProvider.bslglobals.globalfunctions[key].description; returns1C = libProvider.bslglobals.globalfunctions[key].returns; } // tslint:disable-next-line:no-string-literal segmentChar["methods"][key] = { description: methodData.description ? methodData.description : "", alias: methodData.name_en, signature: methodData.signature, returns: methodData.returns, example: methodData.example, signature1C, description1C, returns1C }; } else { // tslint:disable-next-line:no-string-literal if (!segmentChar["properties"]) { // tslint:disable-next-line:no-string-literal segmentChar["properties"] = {}; } const methodData = libProvider.oscriptStdLib.globalvariables[key]; if (libProvider.bslglobals.globalvariables[key]) { description1C = libProvider.bslglobals.globalvariables[key].description; } // tslint:disable-next-line:no-string-literal segmentChar["properties"][key] = { description: methodData.description ? methodData.description : "", alias: methodData.name_en, Доступ: methodData.access, signature: undefined, returns: undefined, description1C }; } } items[element] = segmentChar; } for (const element in classesOscript) { const segment = classesOscript[element]; const segmentChar = this.getSegmentData( segment, false, "OneScript", libProvider.bslglobals.classes[segment.name] ); items[element] = segmentChar; } for (const element in systemEnum) { const segment = systemEnum[element]; const segmentChar = this.getSegmentData( segment, false, "OneScript", libProvider.bslglobals.systemEnum[segment.name] ); items[element] = segmentChar; } return items; } public getStructure(textSyntax: string, syntaxObject: any, oscriptMethods: object): any { let fillStructure = { globalHeader: "Стандартная библиотека классов и функций OneScript", textSyntax, descClass: "", descMethod: "", menuHeight: "100%", elHeight: "100%", classVisible: "none", methodVisible: "none", segmentHeader: "OneScript", methodHeader: "OneScript", displaySwitch: "", switch1C: "Только для OneScript", segmentDescription: "Очень много текста", methodDescription: "Очень много текста", onlyOs: "" }; if (syntaxObject.label === "OneScript") { return this.fillStructureSyntax(fillStructure); } let switch1C = "Только для OneScript"; let methodDescription = "Очень много текста"; const descClass = syntaxObject.description.split("/")[ syntaxObject.description.split("/").length - 1 ]; const descMethod = syntaxObject.label.split(".")[syntaxObject.label.split(".").length - 1]; const alias = oscriptMethods[descClass].alias && oscriptMethods[descClass].alias !== "" ? " / " + oscriptMethods[descClass].alias : ""; const segmentHeader = descClass + alias; const segment = oscriptMethods[descClass]; let segmentDescription = segment.description ? "<p>" + segment.description + "</p>" : ""; segmentDescription = this.fillSegmentData( segmentDescription, segment, "methods", "Методы", "method" ); segmentDescription = this.fillSegmentData( segmentDescription, segment, "properties", "Свойства", "property" ); segmentDescription = this.fillSegmentData( segmentDescription, segment, "constructors", "Конструкторы", "constructor" ); segmentDescription = this.fillSegmentData( segmentDescription, segment, "values", "Значения", "value" ); let methodHeader = "OneScript"; if (descClass !== descMethod) { let methodData; for (const key in oscriptMethods[descClass]) { if (key === "properties" || key === "methods" || key === "values") { for (const item in oscriptMethods[descClass][key]) { if (item === descMethod) { methodData = oscriptMethods[descClass][key][item]; methodHeader = descMethod + (methodData.alias !== "" ? " / " + methodData.alias : ""); if (methodData.description1C || methodData.signature1C) { switch1C = "Описание OneScript<br/>(<span class='a' id = '" + key + "' onclick='switchDescription(this)' style='font-size:1em'>переключить</span>)"; } break; } } } } if (methodData) { methodDescription = ""; if (methodData.description) { methodDescription = methodData.description + "<br/>"; } if (methodData.returns) { methodDescription = methodDescription + "<b><em>Возвращаемое значение: </em></b>" + methodData.returns + "<br/>"; } if (methodData.Доступ) { methodDescription = methodDescription + "<b><em>Доступ: </em></b>" + methodData.Доступ + "<br/>"; } if (methodData.signature) { const stingParams = methodData.signature.default.СтрокаПараметров; methodDescription = methodDescription + "<p><b>Синтаксис:</b></p><p class='hljs'><span class='function_name'>" + descMethod + "</span><span class='parameter_variable'>" + stingParams + "</span></p>"; if (methodData.signature.default.Параметры) { methodDescription = methodDescription + "<p><b>Параметры:</b></p><p>"; for (const param in methodData.signature.default.Параметры) { const paramDescription = "<b><em>" + param + ": </em></b>" + methodData.signature.default.Параметры[param]; methodDescription = methodDescription + paramDescription + "<br/>"; } methodDescription = methodDescription + "</p>"; } } if (methodData.example) { methodDescription = methodDescription + "<p><b>Пример:</b></p><pre class='hljs'>" + methodData.example + "</p>"; } } } fillStructure = { globalHeader: "Стандартная библиотека классов и функций OneScript", textSyntax, descClass, descMethod, menuHeight: "133px", elHeight: descClass !== descMethod ? "120px" : "100%", classVisible: "block", methodVisible: descClass !== descMethod ? "block" : "none", segmentHeader, methodHeader, displaySwitch: "", switch1C, segmentDescription, methodDescription, onlyOs: "" }; return this.fillStructureSyntax(fillStructure); } private fillStructureSyntax(fillStructure) { let globCont = "<h1 style='font-size: 1em;'>Глобальный контекст</h1><ul>"; const structureGlobContext = libProvider.oscriptStdLib.structureMenu; const classesOscript = libProvider.oscriptStdLib.classes; const systemEnum = libProvider.oscriptStdLib.systemEnum; for (const element in structureGlobContext.global) { globCont = globCont + `<li><span class="a" onclick="fillDescription(this)">${element}</span></li>`; } globCont = globCont + `</ul>`; let classes = "<h1 style='font-size: 1em;'>Доступные классы</h1>"; const added = {}; for (const segmentClass in structureGlobContext.classes) { classes = classes + "<h2 style='font-size: 1em;'><em>" + segmentClass + "</em></h2><ul>"; for (const currentClass in structureGlobContext.classes[segmentClass]) { const onlyOs = !libProvider.bslglobals.classes[currentClass] ? "*" : ""; classes = classes + `<li><span class="a" onclick="fillDescription(this)"> ${currentClass + " / " + classesOscript[currentClass].name_en}</span>${onlyOs}</li>`; added[currentClass] = true; if (structureGlobContext.classes[segmentClass][currentClass] !== "") { classes = classes + "<ul>"; for (const childClass in structureGlobContext.classes[segmentClass][ currentClass ]) { added[childClass] = true; classes = classes + `<li><span class="a" onclick="fillDescription(this)"> ${childClass + " / " + classesOscript[childClass].name_en}</span></li>`; } classes = classes + "</ul>"; } } if (segmentClass !== "Прочее") { classes = classes + "</ul>"; } } for (const element in classesOscript) { if (!added[element]) { const onlyOs = !libProvider.bslglobals.classes[element] ? "*" : ""; const alias = classesOscript[element].name_en !== "" ? " / " + classesOscript[element].name_en : ""; classes = classes + `<li><span class="a" onclick="fillDescription(this)">${element + alias}</span>${onlyOs}</li>`; } } classes = classes + "</ul><h1 style='font-size: 1em;'>Системные перечисления</h1><ul>"; for (const element in systemEnum) { const onlyOs = !libProvider.bslglobals.systemEnum[element] ? "*" : ""; const alias = systemEnum[element].name_en !== "" ? " / " + systemEnum[element].name_en : ""; classes = classes + `<li><span class="a" onclick="fillDescription(this)">${element + alias}</span>${onlyOs}</li>`; } fillStructure.globCont = globCont; fillStructure.classes = classes; fillStructure.displaySwitch = "block"; fillStructure.onlyOs = `if (!segment[strSegment][elem].description1C && !segment[strSegment][elem].signature1C){ onlyOs = "*";}`; return fillStructure; } }
the_stack
import { SmartBuffer, SmartBufferOptions } from '../src/smartbuffer'; import { ERRORS, isFiniteInteger, checkEncoding, checkOffsetValue, checkLengthValue, checkTargetOffset } from '../src/utils'; import { assert } from 'chai'; import 'mocha'; describe('Constructing a SmartBuffer', () => { describe('Constructing with an existing Buffer', () => { const buff = new Buffer([0xaa, 0xbb, 0xcc, 0xdd, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99]); const reader = SmartBuffer.fromBuffer(buff); it('should have the exact same internal Buffer when constructed with a Buffer', () => { assert.strictEqual(reader.internalBuffer, buff); }); it('should return a buffer with the same content', () => { assert.deepEqual(reader.toBuffer(), buff); }); }); describe('Constructing with an existing Buffer and setting the encoding', () => { const buff = new Buffer([0xaa, 0xbb, 0xcc, 0xdd, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99]); const reader = SmartBuffer.fromBuffer(buff, 'ascii'); it('should have the exact same internal Buffer', () => { assert.strictEqual(reader.internalBuffer, buff); }); it('should have the same encoding that was set', () => { assert.strictEqual(reader.encoding, 'ascii'); }); }); describe('Constructing with a specified size', () => { const size = 128; const reader = SmartBuffer.fromSize(size); it('should have an internal Buffer with the same length as the size defined in the constructor', () => { assert.strictEqual(reader.internalBuffer.length, size); }); }); describe('Constructing with a specified encoding', () => { const encoding: BufferEncoding = 'utf8'; it('should have an internal encoding with the encoding given to the constructor (1st argument)', () => { const reader = SmartBuffer.fromOptions({ encoding }); assert.strictEqual(reader.encoding, encoding); }); it('should have an internal encoding with the encoding given to the constructor (2nd argument)', () => { const reader = SmartBuffer.fromSize(1024, encoding); assert.strictEqual(reader.encoding, encoding); }); }); describe('Constructing with SmartBufferOptions', () => { const validOptions1: SmartBufferOptions = { size: 1024, encoding: 'ascii' }; const validOptions2: SmartBufferOptions = { buff: Buffer.alloc(1024) }; const validOptions3: SmartBufferOptions = { encoding: 'utf8' }; const invalidOptions1: any = { encoding: 'invalid' }; const invalidOptions2: any = { size: -1 }; const invalidOptions3: any = { buff: 'notabuffer' }; it('should create a SmartBuffer with size 1024 and ascii encoding', () => { const sbuff = SmartBuffer.fromOptions(validOptions1); assert.strictEqual(sbuff.encoding, validOptions1.encoding); assert.strictEqual(sbuff.internalBuffer.length, validOptions1.size); }); it('should create a SmartBuffer with the provided buffer as the initial value', () => { const sbuff = SmartBuffer.fromOptions(validOptions2); assert.deepEqual(sbuff.internalBuffer, validOptions2.buff); }); it('should create a SmartBuffer with the provided ascii encoding, and create a default buffer size', () => { const sbuff = SmartBuffer.fromOptions(validOptions3); assert.strictEqual(sbuff.encoding, validOptions3.encoding); assert.strictEqual(sbuff.internalBuffer.length, 4096); }); it('should throw an error when given an options object with an invalid encoding', () => { assert.throws(() => { // tslint:disable-next-line:no-unused-variable const sbuff = SmartBuffer.fromOptions(invalidOptions1); }); }); it('should throw an error when given an options object with an invalid size', () => { assert.throws(() => { // tslint:disable-next-line:no-unused-variable const sbuff = SmartBuffer.fromOptions(invalidOptions2); }); }); it('should throw an error when given an options object with an invalid buffer', () => { assert.throws(() => { // tslint:disable-next-line:no-unused-variable const sbuff = SmartBuffer.fromOptions(invalidOptions3); }); }); }); describe('Constructing with invalid parameters', () => { it('should throw an exception when given an object that is not a valid SmartBufferOptions object', () => { assert.throws(() => { const invalidOptions: object = {}; const reader = SmartBuffer.fromOptions(invalidOptions); }); }); it('should throw an exception when given an invalid number size', () => { assert.throws(() => { // tslint:disable-next-line:no-unused-variable const reader = SmartBuffer.fromOptions({ size: -100 }); }, Error); }); it('should throw an exception when give a invalid encoding', () => { assert.throws(() => { const invalidEncoding: any = 'invalid'; // tslint:disable-next-line:no-unused-variable const reader = SmartBuffer.fromOptions({ encoding: invalidEncoding }); }, Error); assert.throws(() => { const invalidEncoding: any = 'invalid'; // tslint:disable-next-line:no-unused-variable const reader = SmartBuffer.fromSize(1024, invalidEncoding); }, Error); }); it('should throw and exception when given an object that is not a SmartBufferOptions', () => { assert.throws(() => { // tslint:disable-next-line:no-unused-variable const reader = SmartBuffer.fromOptions(null); }, Error); }); }); describe('Constructing with factory methods', () => { const originalBuffer = new Buffer(10); const sbuff1 = SmartBuffer.fromBuffer(originalBuffer); it('Should create a SmartBuffer with a provided internal Buffer as the initial value', () => { assert.deepEqual(sbuff1.internalBuffer, originalBuffer); }); const sbuff2 = SmartBuffer.fromSize(1024); it('Should create a SmartBuffer with a set provided initial Buffer size', () => { assert.strictEqual(sbuff2.internalBuffer.length, 1024); }); const options: any = { size: 1024, encoding: 'ascii' }; const sbuff3 = SmartBuffer.fromOptions(options); it('Should create a SmartBuffer instance with a given SmartBufferOptions object', () => { assert.strictEqual(sbuff3.encoding, options.encoding); assert.strictEqual(sbuff3.internalBuffer.length, options.size); }); }); }); describe('Reading/Writing To/From SmartBuffer', () => { /** * Technically, if one of these works, they all should. But they're all here anyways. */ describe('Numeric Values', () => { let reader = new SmartBuffer(); reader.writeInt8(0x44); reader.writeUInt8(0xff); reader.writeInt16BE(0x6699); reader.writeInt16LE(0x6699); reader.writeUInt16BE(0xffdd); reader.writeUInt16LE(0xffdd); reader.writeInt32BE(0x77889900); reader.writeInt32LE(0x77889900); reader.writeUInt32BE(0xffddccbb); reader.writeUInt32LE(0xffddccbb); reader.writeFloatBE(1.234); reader.writeFloatLE(1.234); reader.writeDoubleBE(1.23456789); reader.writeDoubleLE(1.23456789); reader.writeUInt8(0xc8, 0); reader.writeUInt16LE(0xc8, 4); reader.insertUInt16LE(0x6699, 6); reader.writeUInt16BE(0x6699); reader.insertUInt16BE(0x6699, reader.length - 1); let iReader = new SmartBuffer(); iReader.insertInt8(0x44, 0); iReader.insertUInt8(0x44, 0); iReader.insertInt16BE(0x6699, 0); iReader.insertInt16LE(0x6699, 0); iReader.insertUInt16BE(0x6699, 0); iReader.insertUInt16LE(0x6699, 0); iReader.insertInt32BE(0x6699, 0); iReader.insertInt32LE(0x6699, 0); iReader.insertUInt32BE(0x6699, 0); iReader.insertUInt32LE(0x6699, 0); iReader.insertFloatBE(0x6699, 0); iReader.insertFloatLE(0x6699, 0); iReader.insertDoubleBE(0x6699, 0); iReader.insertDoubleLE(0x6699, 0); iReader.writeStringNT('h', 2); iReader.insertBuffer(new Buffer('he'), 2); iReader.insertBufferNT(new Buffer('he'), 2); iReader.readInt8(0); it('should equal the correct values that were written above', () => { assert.strictEqual(reader.readUInt8(), 0xc8); assert.strictEqual(reader.readUInt8(), 0xff); assert.strictEqual(reader.readInt16BE(), 0x6699); assert.strictEqual(reader.readInt16LE(), 0xc8); assert.strictEqual(reader.readInt16LE(), 0x6699); assert.strictEqual(reader.readUInt16BE(), 0xffdd); assert.strictEqual(reader.readUInt16LE(), 0xffdd); assert.strictEqual(reader.readInt32BE(), 0x77889900); assert.strictEqual(reader.readInt32LE(), 0x77889900); assert.strictEqual(reader.readUInt32BE(), 0xffddccbb); assert.strictEqual(reader.readUInt32LE(), 0xffddccbb); assert.closeTo(reader.readFloatBE(), 1.234, 0.001); assert.closeTo(reader.readFloatLE(), 1.234, 0.001); assert.closeTo(reader.readDoubleBE(), 1.23456789, 0.001); assert.closeTo(reader.readDoubleLE(), 1.23456789, 0.001); assert.equal(reader.readUInt8(0), 0xc8); }); it('should throw an exception if attempting to read numeric values from a buffer with not enough data left', () => { assert.throws(() => { reader.readUInt32BE(); }); }); it('should throw an exception if attempting to write numeric values to a negative offset.', () => { assert.throws(() => { reader.writeUInt16BE(20, -5); }); }); }); describe('BigInt values', () => { describe('When BigInt is available and so are Buffer methods', () => { before(function() { if (typeof BigInt === 'undefined' || typeof Buffer.prototype.writeBigInt64BE === 'undefined') { this.skip(); } }); it('Reading written-to buffer should read back the results of the insert', () => { const wBuffer = new SmartBuffer(); wBuffer.writeBigInt64LE(BigInt(Number.MAX_SAFE_INTEGER) * BigInt(2)); wBuffer.writeBigInt64BE(BigInt(Number.MAX_SAFE_INTEGER) * BigInt(3)); wBuffer.writeBigUInt64LE(BigInt(Number.MAX_SAFE_INTEGER) * BigInt(4)); wBuffer.writeBigUInt64BE(BigInt(Number.MAX_SAFE_INTEGER) * BigInt(5)); assert.equal(wBuffer.readBigInt64LE(), BigInt(Number.MAX_SAFE_INTEGER) * BigInt(2)); assert.equal(wBuffer.readBigInt64BE(), BigInt(Number.MAX_SAFE_INTEGER) * BigInt(3)); assert.equal(wBuffer.readBigUInt64LE(), BigInt(Number.MAX_SAFE_INTEGER) * BigInt(4)); assert.equal(wBuffer.readBigUInt64BE(), BigInt(Number.MAX_SAFE_INTEGER) * BigInt(5)); }); it('Reading inserted-into buffer should read back the results of the insert', () => { const iBuffer = new SmartBuffer(); iBuffer.insertBigInt64LE(BigInt(Number.MAX_SAFE_INTEGER) * BigInt(6), 0); iBuffer.insertBigInt64BE(BigInt(Number.MAX_SAFE_INTEGER) * BigInt(7), 0); iBuffer.insertBigUInt64LE(BigInt(Number.MAX_SAFE_INTEGER) * BigInt(8), 0); iBuffer.insertBigUInt64BE(BigInt(Number.MAX_SAFE_INTEGER) * BigInt(9), 0); assert.equal(iBuffer.readBigInt64BE(), BigInt(Number.MAX_SAFE_INTEGER) * BigInt(9)); assert.equal(iBuffer.readBigInt64LE(), BigInt(Number.MAX_SAFE_INTEGER) * BigInt(8)); assert.equal(iBuffer.readBigUInt64BE(), BigInt(Number.MAX_SAFE_INTEGER) * BigInt(7)); assert.equal(iBuffer.readBigUInt64LE(), BigInt(Number.MAX_SAFE_INTEGER) * BigInt(6)); }); }); describe('When BigInt is available but buffer methods are not', () => { beforeEach(function () { if (typeof BigInt === 'undefined' || typeof Buffer.prototype.readBigInt64BE === 'function') { this.skip(); } }); const buffer = new SmartBuffer(); // Taking a Number to a BigInt as we do below is semantically invalid, // and implicit casting between Number and BigInt throws a TypeError in // JavaScript. However here, these methods immediately throw the platform // exception, and no cast really takes place. These casts are solely to // satisfy the type checker, as BigInt doesn't exist at runtime in these tests it('Writing throws an exception', () => { assert.throws(() => buffer.writeBigInt64LE(1 as any as bigint), 'Platform does not support Buffer.prototype.writeBigInt64LE.'); assert.throws(() => buffer.writeBigInt64BE(2 as any as bigint), 'Platform does not support Buffer.prototype.writeBigInt64BE.'); assert.throws(() => buffer.writeBigUInt64LE(1 as any as bigint), 'Platform does not support Buffer.prototype.writeBigUInt64LE.'); assert.throws(() => buffer.writeBigUInt64BE(2 as any as bigint), 'Platform does not support Buffer.prototype.writeBigUInt64BE.'); }); it('Inserting throws an exception', () => { assert.throws( () => buffer.insertBigInt64LE(1 as any as bigint, 0), 'Platform does not support Buffer.prototype.writeBigInt64LE.'); assert.throws( () => buffer.insertBigInt64BE(2 as any as bigint, 0), 'Platform does not support Buffer.prototype.writeBigInt64BE.'); assert.throws( () => buffer.insertBigUInt64LE(1 as any as bigint, 0), 'Platform does not support Buffer.prototype.writeBigUInt64LE.'); assert.throws( () => buffer.insertBigUInt64BE(2 as any as bigint, 0), 'Platform does not support Buffer.prototype.writeBigUInt64BE.'); }); it('Reading throws an exception', () => { assert.throws(() => buffer.readBigInt64LE(), 'Platform does not support Buffer.prototype.readBigInt64LE.'); assert.throws(() => buffer.readBigInt64BE(), 'Platform does not support Buffer.prototype.readBigInt64BE.'); assert.throws(() => buffer.readBigUInt64LE(), 'Platform does not support Buffer.prototype.readBigUInt64LE.'); assert.throws(() => buffer.readBigUInt64BE(), 'Platform does not support Buffer.prototype.readBigUInt64BE.'); }); }); describe('When BigInt is unavailable', () => { beforeEach(function () { if (typeof BigInt === 'function') { this.skip(); } }); const buffer = new SmartBuffer(); // Taking a Number to a BigInt as we do below is semantically invalid, // and implicit casting between Number and BigInt throws a TypeError in // JavaScript. However here, these methods immediately throw the platform // exception, and no cast really takes place. These casts are solely to // satisfy the type checker, as BigInt doesn't exist at runtime in these tests it('Writing throws an exception', () => { assert.throws(() => buffer.writeBigInt64LE(1 as any as bigint), 'Platform does not support JS BigInt type.'); assert.throws(() => buffer.writeBigInt64BE(2 as any as bigint), 'Platform does not support JS BigInt type.'); assert.throws(() => buffer.writeBigUInt64LE(1 as any as bigint), 'Platform does not support JS BigInt type.'); assert.throws(() => buffer.writeBigUInt64BE(2 as any as bigint), 'Platform does not support JS BigInt type.'); }); it('Inserting throws an exception', () => { assert.throws(() => buffer.insertBigInt64LE(1 as any as bigint, 0), 'Platform does not support JS BigInt type.'); assert.throws(() => buffer.insertBigInt64BE(2 as any as bigint, 0), 'Platform does not support JS BigInt type.'); assert.throws(() => buffer.insertBigUInt64LE(1 as any as bigint, 0), 'Platform does not support JS BigInt type.'); assert.throws(() => buffer.insertBigUInt64BE(2 as any as bigint, 0), 'Platform does not support JS BigInt type.'); }); it('Reading throws an exception', () => { assert.throws(() => buffer.readBigInt64LE(), 'Platform does not support JS BigInt type.'); assert.throws(() => buffer.readBigInt64BE(), 'Platform does not support JS BigInt type.'); assert.throws(() => buffer.readBigUInt64LE(), 'Platform does not support JS BigInt type.'); assert.throws(() => buffer.readBigUInt64BE(), 'Platform does not support JS BigInt type.'); }); }); }); describe('Basic String Values', () => { let reader = new SmartBuffer(); reader.writeStringNT('hello'); reader.writeString('world'); reader.writeStringNT('✎✏✎✏✎✏'); reader.insertStringNT('first', 0); reader.writeString('hello', 'ascii'); reader.writeString('hello'); it('should equal the correct strings that were written prior', () => { assert.strictEqual(reader.readStringNT(), 'first'); assert.strictEqual(reader.readStringNT(), 'hello'); assert.strictEqual(reader.readString(5), 'world'); assert.strictEqual(reader.readStringNT(), '✎✏✎✏✎✏'); assert.strictEqual(reader.readString(5, 'ascii'), 'hello'); }); it('should throw an exception if passing in an invalid string length to read (infinite)', () => { assert.throws(() => { reader.readString(NaN); }); }); it('should throw an exception if passing in an invalid string length to read (negative)', () => { assert.throws(() => { reader.readString(-5); }); }); it('should throw an exception if passing in an invalid string offset to insert (non number)', () => { assert.throws(() => { const invalidNumber: any = 'sdfdf'; reader.insertString('hello', invalidNumber); }); }); }); describe('Mixed Encoding Strings', () => { let reader = SmartBuffer.fromOptions({ encoding: 'ascii' }); reader.writeStringNT('some ascii text'); reader.writeStringNT('ѕσмє υтƒ8 тєχт', 'utf8'); reader.insertStringNT('first', 0, 'ascii'); it('should equal the correct strings that were written above', () => { assert.strictEqual(reader.readStringNT(), 'first'); assert.strictEqual(reader.readStringNT(), 'some ascii text'); assert.strictEqual(reader.readStringNT('utf8'), 'ѕσмє υтƒ8 тєχт'); }); it('should throw an error when an invalid encoding is provided', () => { assert.throws(() => { // tslint:disable-next-line const invalidBufferType: any = 'invalid'; reader.writeString('hello', invalidBufferType); }); }); it('should throw an error when an invalid encoding is provided along with a valid offset', () => { assert.throws(() => { const invalidBufferType: any = 'invalid'; reader.writeString('hellothere', 2, invalidBufferType); }); }); }); describe('Null/non-null terminating strings', () => { let reader = new SmartBuffer(); reader.writeString('hello\0test\0bleh'); it('should equal hello', () => { assert.strictEqual(reader.readStringNT(), 'hello'); }); it('should equal: test', () => { assert.strictEqual(reader.readString(4), 'test'); }); it('should have a length of zero', () => { assert.strictEqual(reader.readStringNT().length, 0); }); it('should return an empty string', () => { assert.strictEqual(reader.readString(0), ''); }); it('should equal: bleh', () => { assert.strictEqual(reader.readStringNT(), 'bleh'); }); }); describe('Reading string without specifying length', () => { let str = 'hello123'; let writer = new SmartBuffer(); writer.writeString(str); let reader = SmartBuffer.fromBuffer(writer.toBuffer()); assert.strictEqual(reader.readString(), str); }); describe('Write string as specific position', () => { let str = 'hello123'; let writer = new SmartBuffer(); writer.writeString(str, 10); let reader = SmartBuffer.fromBuffer(writer.toBuffer()); reader.readOffset = 10; it('Should read the correct string from the original position it was written to.', () => { assert.strictEqual(reader.readString(), str); }); }); describe('Buffer Values', () => { describe('Writing buffer to position 0', () => { let buff = new SmartBuffer(); let frontBuff = new Buffer([1, 2, 3, 4, 5, 6]); buff.writeStringNT('hello'); buff.writeBuffer(frontBuff, 0); it('should write the buffer to the front of the smart buffer instance', () => { let readBuff = buff.readBuffer(frontBuff.length); assert.deepEqual(readBuff, frontBuff); }); }); describe('Writing null terminated buffer to position 0', () => { let buff = new SmartBuffer(); let frontBuff = new Buffer([1, 2, 3, 4, 5, 6]); buff.writeStringNT('hello'); buff.writeBufferNT(frontBuff, 0); it('should write the buffer to the front of the smart buffer instance', () => { let readBuff = buff.readBufferNT(); assert.deepEqual(readBuff, frontBuff); }); }); describe('Explicit lengths', () => { let buff = new Buffer([0x01, 0x02, 0x04, 0x08, 0x16, 0x32, 0x64]); let reader = new SmartBuffer(); reader.writeBuffer(buff); it('should equal the buffer that was written above.', () => { assert.deepEqual(reader.readBuffer(7), buff); }); }); describe('Implicit lengths', () => { let buff = new Buffer([0x01, 0x02, 0x04, 0x08, 0x16, 0x32, 0x64]); let reader = new SmartBuffer(); reader.writeBuffer(buff); it('should equal the buffer that was written above.', () => { assert.deepEqual(reader.readBuffer(), buff); }); }); describe('Null Terminated Buffer Reading', () => { let buff = new SmartBuffer(); buff.writeBuffer(new Buffer([0x01, 0x02, 0x03, 0x04, 0x00, 0x01, 0x02, 0x03])); let read1 = buff.readBufferNT(); let read2 = buff.readBufferNT(); it('Should return a length of 4 for the four bytes before the first null in the buffer.', () => { assert.equal(read1.length, 4); }); it('Should return a length of 3 for the three bytes after the first null in the buffer after reading to end.', () => { assert.equal(read2.length, 3); }); }); describe('Null Terminated Buffer Writing', () => { let buff = new SmartBuffer(); buff.writeBufferNT(new Buffer([0x01, 0x02, 0x03, 0x04])); let read1 = buff.readBufferNT(); it('Should read the correct null terminated buffer data.', () => { assert.equal(read1.length, 4); }); }); describe('Reading buffer from invalid offset', () => { let buff = new SmartBuffer(); buff.writeBuffer(Buffer.from([1, 2, 3, 4, 5, 6])); it('Should throw an exception if attempting to read a Buffer from an invalid offset', () => { assert.throws(() => { const invalidOffset: any = 'sfsdf'; buff.readBuffer(invalidOffset); }); }); }); describe('Inserting values into specific positions', () => { let reader = new SmartBuffer(); reader.writeUInt16LE(0x0060); reader.writeStringNT('something'); reader.writeUInt32LE(8485934); reader.writeUInt16LE(6699); reader.writeStringNT('else'); reader.insertUInt16LE(reader.length - 2, 2); it('should equal the size of the remaining data in the buffer', () => { reader.readUInt16LE(); let size = reader.readUInt16LE(); assert.strictEqual(reader.remaining(), size); }); }); describe('Adding more data to the buffer than the internal buffer currently allows.', () => { it('Should automatically adjust internal buffer size when needed', () => { let writer = new SmartBuffer(); let largeBuff = new Buffer(10000); writer.writeBuffer(largeBuff); assert.strictEqual(writer.length, largeBuff.length); }); }); }); }); describe('Skipping around data', () => { let writer = new SmartBuffer(); writer.writeStringNT('hello'); writer.writeUInt16LE(6699); writer.writeStringNT('world!'); it('Should equal the UInt16 that was written above', () => { let reader = SmartBuffer.fromBuffer(writer.toBuffer()); reader.readOffset += 6; assert.strictEqual(reader.readUInt16LE(), 6699); reader.readOffset = 0; assert.strictEqual(reader.readStringNT(), 'hello'); reader.readOffset -= 6; assert.strictEqual(reader.readStringNT(), 'hello'); }); it('Should throw an error when attempting to skip more bytes than actually exist.', () => { let reader = SmartBuffer.fromBuffer(writer.toBuffer()); assert.throws(() => { reader.readOffset = 10000; }); }); }); describe('Setting write and read offsets', () => { const writer = SmartBuffer.fromSize(100); writer.writeString('hellotheremynameisjosh'); it('should set the write offset to 10', () => { writer.writeOffset = 10; assert.strictEqual(writer.writeOffset, 10); }); it('should set the read offset to 10', () => { writer.readOffset = 10; assert.strictEqual(writer.readOffset, 10); }); it('should throw an error when given an offset that is out of bounds', () => { assert.throws(() => { writer.readOffset = -1; }); }); it('should throw an error when given an offset that is out of bounds', () => { assert.throws(() => { writer.writeOffset = 1000; }); }); }); describe('Setting encoding', () => { const writer = SmartBuffer.fromSize(100); it('should have utf8 encoding by default', () => { assert.strictEqual(writer.encoding, 'utf8'); }); it('should have ascii encoding after being set', () => { writer.encoding = 'ascii'; assert.strictEqual(writer.encoding, 'ascii'); }); }); describe('Automatic internal buffer resizing', () => { let writer = new SmartBuffer(); it('Should not throw an error when adding data that is larger than current buffer size (internal resize algo fails)', () => { let str = 'String larger than one byte'; writer = SmartBuffer.fromSize(1); writer.writeString(str); assert.strictEqual(writer.internalBuffer.length, str.length); }); it('Should not throw an error when adding data that is larger than current buffer size (internal resize algo succeeds)', () => { writer = SmartBuffer.fromSize(100); let buff = new Buffer(105); writer.writeBuffer(buff); // Test internal array growth algo. assert.strictEqual(writer.internalBuffer.length, 100 * 3 / 2 + 1); }); }); describe('Clearing the buffer', () => { let writer = new SmartBuffer(); writer.writeString('somedata'); it('Should contain some data.', () => { assert.notStrictEqual(writer.length, 0); }); it('Should contain zero data after being cleared.', () => { writer.clear(); assert.strictEqual(writer.length, 0); }); }); describe('Displaying the buffer as a string', () => { let buff = new Buffer([1, 2, 3, 4]); let sbuff = SmartBuffer.fromBuffer(buff); let str = buff.toString(); let str64 = buff.toString('binary'); it('Should return a valid string representing the internal buffer', () => { assert.strictEqual(str, sbuff.toString()); }); it('Should return a valid base64 string representing the internal buffer', () => { assert.strictEqual(str64, sbuff.toString('binary')); }); it('Should throw an error if an invalid encoding is provided', () => { assert.throws(() => { const invalidencoding: any = 'invalid'; let strError = sbuff.toString(invalidencoding); }); }); }); describe('Destroying the buffer', () => { let writer = new SmartBuffer(); writer.writeString('hello123'); writer.destroy(); it('Should have a length of zero when buffer is destroyed', () => { assert.strictEqual(0, writer.length); }); }); describe('ensureWritable()', () => { let sbuff: any = SmartBuffer.fromSize(10); it('should increase the internal buffer size to accomodate given size.', () => { sbuff._ensureWriteable(100); assert.strictEqual(sbuff.internalBuffer.length >= 100, true); }); }); describe('isSmartBufferOptions()', () => { it('should return true when encoding is defined', () => { assert.strictEqual( SmartBuffer.isSmartBufferOptions({ encoding: 'utf8' }), true ); }); it('should return true when size is defined', () => { assert.strictEqual( SmartBuffer.isSmartBufferOptions({ size: 1024 }), true ); }); it('should return true when buff is defined', () => { assert.strictEqual( SmartBuffer.isSmartBufferOptions({ buff: Buffer.alloc(4096) }), true ); }); }); describe('utils', () => { describe('isFiniteInteger', () => { it('should return true for a number that is finite and an integer', () => { assert.equal(isFiniteInteger(10), true); }); it('should return false for a number that is infinite', () => { assert.equal(isFiniteInteger(NaN), false); }); it('should return false for a number that is not an integer', () => { assert.equal(isFiniteInteger(10.1), false); }); }); describe('checkEncoding', () => { it('should throw an exception if a given string is not a valid BufferEncoding', () => { assert.throws(() => { const invalidEncoding: any = 'sdfdf'; checkEncoding(invalidEncoding); }); }); }); });
the_stack
declare class PHASEAmbientMixerDefinition extends PHASEMixerDefinition { static alloc(): PHASEAmbientMixerDefinition; // inherited from NSObject static new(): PHASEAmbientMixerDefinition; // inherited from NSObject readonly inputChannelLayout: AVAudioChannelLayout; readonly orientation: simd_quatf; constructor(o: { channelLayout: AVAudioChannelLayout; orientation: simd_quatf; }); constructor(o: { channelLayout: AVAudioChannelLayout; orientation: simd_quatf; identifier: string; }); initWithChannelLayoutOrientation(layout: AVAudioChannelLayout, orientation: simd_quatf): this; initWithChannelLayoutOrientationIdentifier(layout: AVAudioChannelLayout, orientation: simd_quatf, identifier: string): this; } declare class PHASEAsset extends NSObject { static alloc(): PHASEAsset; // inherited from NSObject static new(): PHASEAsset; // inherited from NSObject readonly identifier: string; } declare const enum PHASEAssetError { FailedToLoad = 1346920801, InvalidEngineInstance = 1346920802, BadParameters = 1346920803, AlreadyExists = 1346920804, GeneralError = 1346920805, MemoryAllocation = 1346920806 } declare var PHASEAssetErrorDomain: string; declare class PHASEAssetRegistry extends NSObject { static alloc(): PHASEAssetRegistry; // inherited from NSObject static new(): PHASEAssetRegistry; // inherited from NSObject readonly globalMetaParameters: NSDictionary<string, PHASEMetaParameter>; assetForIdentifier(identifier: string): PHASEAsset; registerGlobalMetaParameterError(metaParameterDefinition: PHASEMetaParameterDefinition): PHASEGlobalMetaParameterAsset; registerSoundAssetAtURLIdentifierAssetTypeChannelLayoutNormalizationModeError(url: NSURL, identifier: string, assetType: PHASEAssetType, channelLayout: AVAudioChannelLayout, normalizationMode: PHASENormalizationMode): PHASESoundAsset; registerSoundAssetWithDataIdentifierFormatNormalizationModeError(data: NSData, identifier: string, format: AVAudioFormat, normalizationMode: PHASENormalizationMode): PHASESoundAsset; registerSoundEventAssetWithRootNodeIdentifierError(rootNode: PHASESoundEventNodeDefinition, identifier: string): PHASESoundEventNodeAsset; unregisterAssetWithIdentifierCompletion(identifier: string, handler: (p1: boolean) => void): void; } declare const enum PHASEAssetType { Resident = 0, Streamed = 1 } declare class PHASEBlendNodeDefinition extends PHASESoundEventNodeDefinition { static alloc(): PHASEBlendNodeDefinition; // inherited from NSObject static new(): PHASEBlendNodeDefinition; // inherited from NSObject readonly blendParameterDefinition: PHASENumberMetaParameterDefinition; readonly spatialMixerDefinitionForDistance: PHASESpatialMixerDefinition; constructor(o: { distanceBlendWithSpatialMixerDefinition: PHASESpatialMixerDefinition; }); constructor(o: { distanceBlendWithSpatialMixerDefinition: PHASESpatialMixerDefinition; identifier: string; }); constructor(o: { blendMetaParameterDefinition: PHASENumberMetaParameterDefinition; }); constructor(o: { blendMetaParameterDefinition: PHASENumberMetaParameterDefinition; identifier: string; }); addRangeForInputValuesAboveFullGainAtValueFadeCurveTypeSubtree(value: number, fullGainAtValue: number, fadeCurveType: PHASECurveType, subtree: PHASESoundEventNodeDefinition): void; addRangeForInputValuesBelowFullGainAtValueFadeCurveTypeSubtree(value: number, fullGainAtValue: number, fadeCurveType: PHASECurveType, subtree: PHASESoundEventNodeDefinition): void; addRangeForInputValuesBetweenHighValueFullGainAtLowValueFullGainAtHighValueLowFadeCurveTypeHighFadeCurveTypeSubtree(lowValue: number, highValue: number, fullGainAtLowValue: number, fullGainAtHighValue: number, lowFadeCurveType: PHASECurveType, highFadeCurveType: PHASECurveType, subtree: PHASESoundEventNodeDefinition): void; addRangeWithEnvelopeSubtree(envelope: PHASEEnvelope, subtree: PHASESoundEventNodeDefinition): void; initDistanceBlendWithSpatialMixerDefinition(spatialMixerDefinition: PHASESpatialMixerDefinition): this; initDistanceBlendWithSpatialMixerDefinitionIdentifier(spatialMixerDefinition: PHASESpatialMixerDefinition, identifier: string): this; initWithBlendMetaParameterDefinition(blendMetaParameterDefinition: PHASENumberMetaParameterDefinition): this; initWithBlendMetaParameterDefinitionIdentifier(blendMetaParameterDefinition: PHASENumberMetaParameterDefinition, identifier: string): this; } declare const enum PHASECalibrationMode { None = 0, RelativeSpl = 1, AbsoluteSpl = 2 } declare class PHASECardioidDirectivityModelParameters extends PHASEDirectivityModelParameters { static alloc(): PHASECardioidDirectivityModelParameters; // inherited from NSObject static new(): PHASECardioidDirectivityModelParameters; // inherited from NSObject readonly subbandParameters: NSArray<PHASECardioidDirectivityModelSubbandParameters>; constructor(o: { subbandParameters: NSArray<PHASECardioidDirectivityModelSubbandParameters> | PHASECardioidDirectivityModelSubbandParameters[]; }); initWithSubbandParameters(subbandParameters: NSArray<PHASECardioidDirectivityModelSubbandParameters> | PHASECardioidDirectivityModelSubbandParameters[]): this; } declare class PHASECardioidDirectivityModelSubbandParameters extends NSObject { static alloc(): PHASECardioidDirectivityModelSubbandParameters; // inherited from NSObject static new(): PHASECardioidDirectivityModelSubbandParameters; // inherited from NSObject frequency: number; pattern: number; sharpness: number; } declare class PHASEChannelMixerDefinition extends PHASEMixerDefinition { static alloc(): PHASEChannelMixerDefinition; // inherited from NSObject static new(): PHASEChannelMixerDefinition; // inherited from NSObject readonly inputChannelLayout: AVAudioChannelLayout; constructor(o: { channelLayout: AVAudioChannelLayout; }); constructor(o: { channelLayout: AVAudioChannelLayout; identifier: string; }); initWithChannelLayout(layout: AVAudioChannelLayout): this; initWithChannelLayoutIdentifier(layout: AVAudioChannelLayout, identifier: string): this; } declare class PHASEConeDirectivityModelParameters extends PHASEDirectivityModelParameters { static alloc(): PHASEConeDirectivityModelParameters; // inherited from NSObject static new(): PHASEConeDirectivityModelParameters; // inherited from NSObject readonly subbandParameters: NSArray<PHASEConeDirectivityModelSubbandParameters>; constructor(o: { subbandParameters: NSArray<PHASEConeDirectivityModelSubbandParameters> | PHASEConeDirectivityModelSubbandParameters[]; }); initWithSubbandParameters(subbandParameters: NSArray<PHASEConeDirectivityModelSubbandParameters> | PHASEConeDirectivityModelSubbandParameters[]): this; } declare class PHASEConeDirectivityModelSubbandParameters extends NSObject { static alloc(): PHASEConeDirectivityModelSubbandParameters; // inherited from NSObject static new(): PHASEConeDirectivityModelSubbandParameters; // inherited from NSObject frequency: number; readonly innerAngle: number; readonly outerAngle: number; outerGain: number; setInnerAngleOuterAngle(innerAngle: number, outerAngle: number): void; } declare class PHASEContainerNodeDefinition extends PHASESoundEventNodeDefinition { static alloc(): PHASEContainerNodeDefinition; // inherited from NSObject static new(): PHASEContainerNodeDefinition; // inherited from NSObject constructor(o: { identifier: string; }); addSubtree(subtree: PHASESoundEventNodeDefinition): void; initWithIdentifier(identifier: string): this; } declare const enum PHASECullOption { Terminate = 0, SleepWakeAtZero = 1, SleepWakeAtRandomOffset = 2, SleepWakeAtRealtimeOffset = 3, DoNotCull = 4 } declare const enum PHASECurveType { Linear = 1668435054, Squared = 1668436849, InverseSquared = 1668434257, Cubed = 1668432757, InverseCubed = 1668434243, Sine = 1668436846, InverseSine = 1668434259, Sigmoid = 1668436839, InverseSigmoid = 1668434247 } declare class PHASEDefinition extends NSObject { static alloc(): PHASEDefinition; // inherited from NSObject static new(): PHASEDefinition; // inherited from NSObject readonly identifier: string; } declare class PHASEDirectivityModelParameters extends NSObject { static alloc(): PHASEDirectivityModelParameters; // inherited from NSObject static new(): PHASEDirectivityModelParameters; // inherited from NSObject } declare class PHASEDistanceModelFadeOutParameters extends NSObject { static alloc(): PHASEDistanceModelFadeOutParameters; // inherited from NSObject static new(): PHASEDistanceModelFadeOutParameters; // inherited from NSObject readonly cullDistance: number; constructor(o: { cullDistance: number; }); initWithCullDistance(cullDistance: number): this; } declare class PHASEDistanceModelParameters extends NSObject { static alloc(): PHASEDistanceModelParameters; // inherited from NSObject static new(): PHASEDistanceModelParameters; // inherited from NSObject fadeOutParameters: PHASEDistanceModelFadeOutParameters; } declare class PHASEDucker extends NSObject { static alloc(): PHASEDucker; // inherited from NSObject static new(): PHASEDucker; // inherited from NSObject readonly active: boolean; readonly attackCurve: PHASECurveType; readonly attackTime: number; readonly gain: number; readonly identifier: string; readonly releaseCurve: PHASECurveType; readonly releaseTime: number; readonly sourceGroups: NSSet<PHASEGroup>; readonly targetGroups: NSSet<PHASEGroup>; constructor(o: { engine: PHASEEngine; sourceGroups: NSSet<PHASEGroup>; targetGroups: NSSet<PHASEGroup>; gain: number; attackTime: number; releaseTime: number; attackCurve: PHASECurveType; releaseCurve: PHASECurveType; }); activate(): void; deactivate(): void; initWithEngineSourceGroupsTargetGroupsGainAttackTimeReleaseTimeAttackCurveReleaseCurve(engine: PHASEEngine, sourceGroups: NSSet<PHASEGroup>, targetGroups: NSSet<PHASEGroup>, gain: number, attackTime: number, releaseTime: number, attackCurve: PHASECurveType, releaseCurve: PHASECurveType): this; } declare class PHASEEngine extends NSObject { static alloc(): PHASEEngine; // inherited from NSObject static new(): PHASEEngine; // inherited from NSObject readonly activeGroupPreset: PHASEGroupPreset; readonly assetRegistry: PHASEAssetRegistry; defaultMedium: PHASEMedium; defaultReverbPreset: PHASEReverbPreset; readonly duckers: NSArray<PHASEDucker>; readonly groups: NSDictionary<string, PHASEGroup>; outputSpatializationMode: PHASESpatializationMode; readonly renderingState: PHASERenderingState; readonly rootObject: PHASEObject; readonly soundEvents: NSArray<PHASESoundEvent>; unitsPerMeter: number; unitsPerSecond: number; constructor(o: { updateMode: PHASEUpdateMode; }); initWithUpdateMode(updateMode: PHASEUpdateMode): this; pause(): void; startAndReturnError(): boolean; stop(): void; update(): void; } declare class PHASEEnvelope extends NSObject { static alloc(): PHASEEnvelope; // inherited from NSObject static new(): PHASEEnvelope; // inherited from NSObject readonly domain: PHASENumericPair; readonly range: PHASENumericPair; readonly segments: NSArray<PHASEEnvelopeSegment>; readonly startPoint: interop.Reference<number>; constructor(o: { startPoint: interop.Reference<number>; segments: NSArray<PHASEEnvelopeSegment> | PHASEEnvelopeSegment[]; }); evaluateForValue(x: number): number; initWithStartPointSegments(startPoint: interop.Reference<number>, segments: NSArray<PHASEEnvelopeSegment> | PHASEEnvelopeSegment[]): this; } declare class PHASEEnvelopeDistanceModelParameters extends PHASEDistanceModelParameters { static alloc(): PHASEEnvelopeDistanceModelParameters; // inherited from NSObject static new(): PHASEEnvelopeDistanceModelParameters; // inherited from NSObject readonly envelope: PHASEEnvelope; constructor(o: { envelope: PHASEEnvelope; }); initWithEnvelope(envelope: PHASEEnvelope): this; } declare class PHASEEnvelopeSegment extends NSObject { static alloc(): PHASEEnvelopeSegment; // inherited from NSObject static new(): PHASEEnvelopeSegment; // inherited from NSObject curveType: PHASECurveType; endPoint: interop.Reference<number>; constructor(o: { endPoint: interop.Reference<number>; curveType: PHASECurveType; }); initWithEndPointCurveType(endPoint: interop.Reference<number>, curveType: PHASECurveType): this; } declare const enum PHASEError { InitializeFailed = 1346913633 } declare var PHASEErrorDomain: string; declare class PHASEGeneratorNodeDefinition extends PHASESoundEventNodeDefinition { static alloc(): PHASEGeneratorNodeDefinition; // inherited from NSObject static new(): PHASEGeneratorNodeDefinition; // inherited from NSObject readonly calibrationMode: PHASECalibrationMode; gainMetaParameterDefinition: PHASENumberMetaParameterDefinition; group: PHASEGroup; readonly level: number; readonly mixerDefinition: PHASEMixerDefinition; rate: number; rateMetaParameterDefinition: PHASENumberMetaParameterDefinition; setCalibrationModeLevel(calibrationMode: PHASECalibrationMode, level: number): void; } declare class PHASEGeneratorParameters extends NSObject { static alloc(): PHASEGeneratorParameters; // inherited from NSObject static new(): PHASEGeneratorParameters; // inherited from NSObject gain: number; rate: number; } declare class PHASEGeometricSpreadingDistanceModelParameters extends PHASEDistanceModelParameters { static alloc(): PHASEGeometricSpreadingDistanceModelParameters; // inherited from NSObject static new(): PHASEGeometricSpreadingDistanceModelParameters; // inherited from NSObject rolloffFactor: number; } declare class PHASEGlobalMetaParameterAsset extends PHASEAsset { static alloc(): PHASEGlobalMetaParameterAsset; // inherited from NSObject static new(): PHASEGlobalMetaParameterAsset; // inherited from NSObject } declare class PHASEGroup extends NSObject { static alloc(): PHASEGroup; // inherited from NSObject static new(): PHASEGroup; // inherited from NSObject gain: number; readonly identifier: string; readonly muted: boolean; rate: number; readonly soloed: boolean; constructor(o: { identifier: string; }); fadeGainDurationCurveType(gain: number, duration: number, curveType: PHASECurveType): void; fadeRateDurationCurveType(rate: number, duration: number, curveType: PHASECurveType): void; initWithIdentifier(identifier: string): this; mute(): void; registerWithEngine(engine: PHASEEngine): void; solo(): void; unmute(): void; unregisterFromEngine(): void; unsolo(): void; } declare class PHASEGroupPreset extends NSObject { static alloc(): PHASEGroupPreset; // inherited from NSObject static new(): PHASEGroupPreset; // inherited from NSObject readonly settings: NSDictionary<string, PHASEGroupPresetSetting>; readonly timeToReset: number; readonly timeToTarget: number; constructor(o: { engine: PHASEEngine; settings: NSDictionary<string, PHASEGroupPresetSetting>; timeToTarget: number; timeToReset: number; }); activate(): void; activateWithTimeToTargetOverride(timeToTargetOverride: number): void; deactivate(): void; deactivateWithTimeToResetOverride(timeToResetOverride: number): void; initWithEngineSettingsTimeToTargetTimeToReset(engine: PHASEEngine, settings: NSDictionary<string, PHASEGroupPresetSetting>, timeToTarget: number, timeToReset: number): this; } declare class PHASEGroupPresetSetting extends NSObject { static alloc(): PHASEGroupPresetSetting; // inherited from NSObject static new(): PHASEGroupPresetSetting; // inherited from NSObject readonly gain: number; readonly gainCurveType: PHASECurveType; readonly rate: number; readonly rateCurveType: PHASECurveType; constructor(o: { gain: number; rate: number; gainCurveType: PHASECurveType; rateCurveType: PHASECurveType; }); initWithGainRateGainCurveTypeRateCurveType(gain: number, rate: number, gainCurveType: PHASECurveType, rateCurveType: PHASECurveType): this; } declare class PHASEListener extends PHASEObject { static alloc(): PHASEListener; // inherited from NSObject static new(): PHASEListener; // inherited from NSObject gain: number; } declare class PHASEMappedMetaParameterDefinition extends PHASENumberMetaParameterDefinition { static alloc(): PHASEMappedMetaParameterDefinition; // inherited from NSObject static new(): PHASEMappedMetaParameterDefinition; // inherited from NSObject readonly envelope: PHASEEnvelope; readonly inputMetaParameterDefinition: PHASENumberMetaParameterDefinition; constructor(o: { inputMetaParameterDefinition: PHASENumberMetaParameterDefinition; envelope: PHASEEnvelope; }); constructor(o: { inputMetaParameterDefinition: PHASENumberMetaParameterDefinition; envelope: PHASEEnvelope; identifier: string; }); initWithInputMetaParameterDefinitionEnvelope(inputMetaParameterDefinition: PHASENumberMetaParameterDefinition, envelope: PHASEEnvelope): this; initWithInputMetaParameterDefinitionEnvelopeIdentifier(inputMetaParameterDefinition: PHASENumberMetaParameterDefinition, envelope: PHASEEnvelope, identifier: string): this; } declare class PHASEMaterial extends NSObject { static alloc(): PHASEMaterial; // inherited from NSObject static new(): PHASEMaterial; // inherited from NSObject constructor(o: { engine: PHASEEngine; preset: PHASEMaterialPreset; }); initWithEnginePreset(engine: PHASEEngine, preset: PHASEMaterialPreset): this; } declare const enum PHASEMaterialPreset { Cardboard = 1833136740, Glass = 1833397363, Brick = 1833071211, Concrete = 1833132914, Drywall = 1833202295, Wood = 1834448228 } declare class PHASEMedium extends NSObject { static alloc(): PHASEMedium; // inherited from NSObject static new(): PHASEMedium; // inherited from NSObject constructor(o: { engine: PHASEEngine; preset: PHASEMediumPreset; }); initWithEnginePreset(engine: PHASEEngine, preset: PHASEMediumPreset): this; } declare const enum PHASEMediumPreset { Air = 1835286898 } declare class PHASEMetaParameter extends NSObject { static alloc(): PHASEMetaParameter; // inherited from NSObject static new(): PHASEMetaParameter; // inherited from NSObject readonly identifier: string; value: any; } declare class PHASEMetaParameterDefinition extends PHASEDefinition { static alloc(): PHASEMetaParameterDefinition; // inherited from NSObject static new(): PHASEMetaParameterDefinition; // inherited from NSObject readonly value: any; } declare class PHASEMixer extends NSObject { static alloc(): PHASEMixer; // inherited from NSObject static new(): PHASEMixer; // inherited from NSObject readonly gain: number; readonly gainMetaParameter: PHASEMetaParameter; readonly identifier: string; } declare class PHASEMixerDefinition extends PHASEDefinition { static alloc(): PHASEMixerDefinition; // inherited from NSObject static new(): PHASEMixerDefinition; // inherited from NSObject gain: number; gainMetaParameterDefinition: PHASENumberMetaParameterDefinition; } declare class PHASEMixerParameters extends NSObject { static alloc(): PHASEMixerParameters; // inherited from NSObject static new(): PHASEMixerParameters; // inherited from NSObject addAmbientMixerParametersWithIdentifierListener(identifier: string, listener: PHASEListener): void; addSpatialMixerParametersWithIdentifierSourceListener(identifier: string, source: PHASESource, listener: PHASEListener): void; } declare const enum PHASENormalizationMode { None = 0, Dynamic = 1 } declare class PHASENumberMetaParameter extends PHASEMetaParameter { static alloc(): PHASENumberMetaParameter; // inherited from NSObject static new(): PHASENumberMetaParameter; // inherited from NSObject readonly maximum: number; readonly minimum: number; fadeToValueDuration(value: number, duration: number): void; } declare class PHASENumberMetaParameterDefinition extends PHASEMetaParameterDefinition { static alloc(): PHASENumberMetaParameterDefinition; // inherited from NSObject static new(): PHASENumberMetaParameterDefinition; // inherited from NSObject readonly maximum: number; readonly minimum: number; constructor(o: { value: number; }); constructor(o: { value: number; identifier: string; }); constructor(o: { value: number; minimum: number; maximum: number; }); constructor(o: { value: number; minimum: number; maximum: number; identifier: string; }); initWithValue(value: number): this; initWithValueIdentifier(value: number, identifier: string): this; initWithValueMinimumMaximum(value: number, minimum: number, maximum: number): this; initWithValueMinimumMaximumIdentifier(value: number, minimum: number, maximum: number, identifier: string): this; } declare class PHASENumericPair extends NSObject { static alloc(): PHASENumericPair; // inherited from NSObject static new(): PHASENumericPair; // inherited from NSObject first: number; second: number; constructor(o: { firstValue: number; secondValue: number; }); initWithFirstValueSecondValue(first: number, second: number): this; } declare class PHASEObject extends NSObject implements NSCopying { static alloc(): PHASEObject; // inherited from NSObject static new(): PHASEObject; // inherited from NSObject readonly children: NSArray<PHASEObject>; readonly parent: PHASEObject; transform: simd_float4x4; worldTransform: simd_float4x4; static readonly forward: interop.Reference<number>; static readonly right: interop.Reference<number>; static readonly up: interop.Reference<number>; constructor(o: { engine: PHASEEngine; }); addChildError(child: PHASEObject): boolean; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; initWithEngine(engine: PHASEEngine): this; removeChild(child: PHASEObject): void; removeChildren(): void; } declare class PHASEOccluder extends PHASEObject { static alloc(): PHASEOccluder; // inherited from NSObject static new(): PHASEOccluder; // inherited from NSObject readonly shapes: NSArray<PHASEShape>; constructor(o: { engine: PHASEEngine; shapes: NSArray<PHASEShape> | PHASEShape[]; }); initWithEngineShapes(engine: PHASEEngine, shapes: NSArray<PHASEShape> | PHASEShape[]): this; } declare const enum PHASEPlaybackMode { OneShot = 0, Looping = 1 } declare const enum PHASEPushStreamBufferOptions { Default = 1, Loops = 2, Interrupts = 4, InterruptsAtLoop = 8 } declare const enum PHASEPushStreamCompletionCallbackCondition { DataRendered = 0 } declare class PHASEPushStreamNode extends NSObject { static alloc(): PHASEPushStreamNode; // inherited from NSObject static new(): PHASEPushStreamNode; // inherited from NSObject readonly format: AVAudioFormat; readonly gainMetaParameter: PHASENumberMetaParameter; readonly mixer: PHASEMixer; readonly rateMetaParameter: PHASENumberMetaParameter; scheduleBuffer(buffer: AVAudioPCMBuffer): void; scheduleBufferAtTimeOptions(buffer: AVAudioPCMBuffer, when: AVAudioTime, options: PHASEPushStreamBufferOptions): void; scheduleBufferAtTimeOptionsCompletionCallbackTypeCompletionHandler(buffer: AVAudioPCMBuffer, when: AVAudioTime, options: PHASEPushStreamBufferOptions, completionCallbackType: PHASEPushStreamCompletionCallbackCondition, completionHandler: (p1: PHASEPushStreamCompletionCallbackCondition) => void): void; scheduleBufferCompletionCallbackTypeCompletionHandler(buffer: AVAudioPCMBuffer, completionCallbackType: PHASEPushStreamCompletionCallbackCondition, completionHandler: (p1: PHASEPushStreamCompletionCallbackCondition) => void): void; } declare class PHASEPushStreamNodeDefinition extends PHASEGeneratorNodeDefinition { static alloc(): PHASEPushStreamNodeDefinition; // inherited from NSObject static new(): PHASEPushStreamNodeDefinition; // inherited from NSObject readonly format: AVAudioFormat; normalize: boolean; constructor(o: { mixerDefinition: PHASEMixerDefinition; format: AVAudioFormat; }); constructor(o: { mixerDefinition: PHASEMixerDefinition; format: AVAudioFormat; identifier: string; }); initWithMixerDefinitionFormat(mixerDefinition: PHASEMixerDefinition, format: AVAudioFormat): this; initWithMixerDefinitionFormatIdentifier(mixerDefinition: PHASEMixerDefinition, format: AVAudioFormat, identifier: string): this; } declare class PHASERandomNodeDefinition extends PHASESoundEventNodeDefinition { static alloc(): PHASERandomNodeDefinition; // inherited from NSObject static new(): PHASERandomNodeDefinition; // inherited from NSObject uniqueSelectionQueueLength: number; constructor(o: { identifier: string; }); addSubtreeWeight(subtree: PHASESoundEventNodeDefinition, weight: number): void; initWithIdentifier(identifier: string): this; } declare const enum PHASERenderingState { Stopped = 0, Started = 1, Paused = 2 } declare const enum PHASEReverbPreset { None = 1917742958, SmallRoom = 1918063213, MediumRoom = 1917669997, LargeRoom = 1917604401, LargeRoom2 = 1917604402, MediumChamber = 1917666152, LargeChamber = 1917600616, MediumHall = 1917667377, MediumHall2 = 1917667378, MediumHall3 = 1917667379, LargeHall = 1917601841, LargeHall2 = 1917601842, Cathedral = 1917023336 } declare class PHASESamplerNodeDefinition extends PHASEGeneratorNodeDefinition { static alloc(): PHASESamplerNodeDefinition; // inherited from NSObject static new(): PHASESamplerNodeDefinition; // inherited from NSObject readonly assetIdentifier: string; cullOption: PHASECullOption; playbackMode: PHASEPlaybackMode; constructor(o: { soundAssetIdentifier: string; mixerDefinition: PHASEMixerDefinition; }); constructor(o: { soundAssetIdentifier: string; mixerDefinition: PHASEMixerDefinition; identifier: string; }); initWithSoundAssetIdentifierMixerDefinition(soundAssetIdentifier: string, mixerDefinition: PHASEMixerDefinition): this; initWithSoundAssetIdentifierMixerDefinitionIdentifier(soundAssetIdentifier: string, mixerDefinition: PHASEMixerDefinition, identifier: string): this; } declare class PHASEShape extends NSObject implements NSCopying { static alloc(): PHASEShape; // inherited from NSObject static new(): PHASEShape; // inherited from NSObject readonly elements: NSArray<PHASEShapeElement>; constructor(o: { engine: PHASEEngine; mesh: MDLMesh; }); constructor(o: { engine: PHASEEngine; mesh: MDLMesh; materials: NSArray<PHASEMaterial> | PHASEMaterial[]; }); copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; initWithEngineMesh(engine: PHASEEngine, mesh: MDLMesh): this; initWithEngineMeshMaterials(engine: PHASEEngine, mesh: MDLMesh, materials: NSArray<PHASEMaterial> | PHASEMaterial[]): this; } declare class PHASEShapeElement extends NSObject { static alloc(): PHASEShapeElement; // inherited from NSObject static new(): PHASEShapeElement; // inherited from NSObject material: PHASEMaterial; } declare class PHASESoundAsset extends PHASEAsset { static alloc(): PHASESoundAsset; // inherited from NSObject static new(): PHASESoundAsset; // inherited from NSObject readonly data: NSData; readonly type: PHASEAssetType; readonly url: NSURL; } declare class PHASESoundEvent extends NSObject { static alloc(): PHASESoundEvent; // inherited from NSObject static new(): PHASESoundEvent; // inherited from NSObject readonly indefinite: boolean; readonly metaParameters: NSDictionary<string, PHASEMetaParameter>; readonly mixers: NSDictionary<string, PHASEMixer>; readonly prepareState: PHASESoundEventPrepareState; readonly pushStreamNodes: NSDictionary<string, PHASEPushStreamNode>; readonly renderingState: PHASERenderingState; constructor(o: { engine: PHASEEngine; assetIdentifier: string; }); constructor(o: { engine: PHASEEngine; assetIdentifier: string; mixerParameters: PHASEMixerParameters; }); initWithEngineAssetIdentifierError(engine: PHASEEngine, assetIdentifier: string): this; initWithEngineAssetIdentifierMixerParametersError(engine: PHASEEngine, assetIdentifier: string, mixerParameters: PHASEMixerParameters): this; pause(): void; prepareWithCompletion(handler: (p1: PHASESoundEventPrepareHandlerReason) => void): void; resume(): void; seekToTimeCompletion(time: number, handler: (p1: PHASESoundEventSeekHandlerReason) => void): void; startWithCompletion(handler: (p1: PHASESoundEventStartHandlerReason) => void): void; stopAndInvalidate(): void; } declare const enum PHASESoundEventError { NotFound = 1346925665, BadData = 1346925666, InvalidInstance = 1346925667, APIMisuse = 1346925668, SystemNotInitialized = 1346925669, OutOfMemory = 1346925670 } declare var PHASESoundEventErrorDomain: string; declare class PHASESoundEventNodeAsset extends PHASEAsset { static alloc(): PHASESoundEventNodeAsset; // inherited from NSObject static new(): PHASESoundEventNodeAsset; // inherited from NSObject } declare class PHASESoundEventNodeDefinition extends PHASEDefinition { static alloc(): PHASESoundEventNodeDefinition; // inherited from NSObject static new(): PHASESoundEventNodeDefinition; // inherited from NSObject readonly children: NSArray<PHASESoundEventNodeDefinition>; } declare const enum PHASESoundEventPrepareHandlerReason { Failure = 0, Prepared = 1, Terminated = 2 } declare const enum PHASESoundEventPrepareState { PrepareNotStarted = 0, PrepareInProgress = 1, Prepared = 2 } declare const enum PHASESoundEventSeekHandlerReason { Failure = 0, FailureSeekAlreadyInProgress = 1, SeekSuccessful = 2 } declare const enum PHASESoundEventStartHandlerReason { Failure = 0, FinishedPlaying = 1, Terminated = 2 } declare class PHASESource extends PHASEObject { static alloc(): PHASESource; // inherited from NSObject static new(): PHASESource; // inherited from NSObject gain: number; readonly shapes: NSArray<PHASEShape>; constructor(o: { engine: PHASEEngine; shapes: NSArray<PHASEShape> | PHASEShape[]; }); initWithEngineShapes(engine: PHASEEngine, shapes: NSArray<PHASEShape> | PHASEShape[]): this; } declare var PHASESpatialCategoryDirectPathTransmission: string; declare var PHASESpatialCategoryEarlyReflections: string; declare var PHASESpatialCategoryLateReverb: string; declare class PHASESpatialMixerDefinition extends PHASEMixerDefinition { static alloc(): PHASESpatialMixerDefinition; // inherited from NSObject static new(): PHASESpatialMixerDefinition; // inherited from NSObject distanceModelParameters: PHASEDistanceModelParameters; listenerDirectivityModelParameters: PHASEDirectivityModelParameters; sourceDirectivityModelParameters: PHASEDirectivityModelParameters; readonly spatialPipeline: PHASESpatialPipeline; constructor(o: { spatialPipeline: PHASESpatialPipeline; }); constructor(o: { spatialPipeline: PHASESpatialPipeline; identifier: string; }); initWithSpatialPipeline(spatialPipeline: PHASESpatialPipeline): this; initWithSpatialPipelineIdentifier(spatialPipeline: PHASESpatialPipeline, identifier: string): this; } declare class PHASESpatialPipeline extends NSObject { static alloc(): PHASESpatialPipeline; // inherited from NSObject static new(): PHASESpatialPipeline; // inherited from NSObject readonly entries: NSDictionary<string, PHASESpatialPipelineEntry>; readonly flags: PHASESpatialPipelineFlags; constructor(o: { flags: PHASESpatialPipelineFlags; }); initWithFlags(flags: PHASESpatialPipelineFlags): this; } declare class PHASESpatialPipelineEntry extends NSObject { static alloc(): PHASESpatialPipelineEntry; // inherited from NSObject static new(): PHASESpatialPipelineEntry; // inherited from NSObject sendLevel: number; sendLevelMetaParameterDefinition: PHASENumberMetaParameterDefinition; } declare const enum PHASESpatialPipelineFlags { DirectPathTransmission = 1, EarlyReflections = 2, LateReverb = 4 } declare const enum PHASESpatializationMode { Automatic = 0, AlwaysUseBinaural = 1, AlwaysUseChannelBased = 2 } declare class PHASEStringMetaParameter extends PHASEMetaParameter { static alloc(): PHASEStringMetaParameter; // inherited from NSObject static new(): PHASEStringMetaParameter; // inherited from NSObject } declare class PHASEStringMetaParameterDefinition extends PHASEMetaParameterDefinition { static alloc(): PHASEStringMetaParameterDefinition; // inherited from NSObject static new(): PHASEStringMetaParameterDefinition; // inherited from NSObject constructor(o: { value: string; }); constructor(o: { value: string; identifier: string; }); initWithValue(value: string): this; initWithValueIdentifier(value: string, identifier: string): this; } declare class PHASESwitchNodeDefinition extends PHASESoundEventNodeDefinition { static alloc(): PHASESwitchNodeDefinition; // inherited from NSObject static new(): PHASESwitchNodeDefinition; // inherited from NSObject readonly switchMetaParameterDefinition: PHASEStringMetaParameterDefinition; constructor(o: { switchMetaParameterDefinition: PHASEStringMetaParameterDefinition; }); constructor(o: { switchMetaParameterDefinition: PHASEStringMetaParameterDefinition; identifier: string; }); addSubtreeSwitchValue(subtree: PHASESoundEventNodeDefinition, switchValue: string): void; initWithSwitchMetaParameterDefinition(switchMetaParameterDefinition: PHASEStringMetaParameterDefinition): this; initWithSwitchMetaParameterDefinitionIdentifier(switchMetaParameterDefinition: PHASEStringMetaParameterDefinition, identifier: string): this; } declare const enum PHASEUpdateMode { Automatic = 0, Manual = 1 }
the_stack
import { PdfDocument, PdfPage, PdfStandardFont, PdfTrueTypeFont, PdfGrid } from './../../../src/index'; import { PdfSolidBrush, PdfColor, PdfFont, PdfFontFamily, PdfStringFormat } from './../../../src/index'; import { RectangleF, PdfPen, PdfGraphicsState, PdfFontStyle, PdfTextAlignment,PdfPath, PointF, PdfFillMode , PdfLayoutBreakType, PdfLayoutType, PdfLayoutFormat} from './../../../src/index'; import { Utils } from './../utils.spec'; import { PdfShapeElement } from '../../../src/implementation/graphics/figures/base/pdf-shape-element'; import { ShapeLayouter } from '../../../src/implementation/graphics/figures/base/shape-layouter'; describe('UTC-01: Drawing path', () => { it('-EJ2-38402 Drawing path1', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); //Draw PDF path to page. path.draw(page1, new PointF(0, 0)); //document.save("EJ2_38402_draw_path1.pdf"); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path1.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-02: Drawing path', () => { it('-EJ2-38402 Drawing path2', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); // set pen let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // set brush let brush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); // draw the path page1.graphics.drawPath(pen, brush, path); // save the document. //document.save('EJ2_38402_draw_path2.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path2.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-03: Drawing path', () => { it('-EJ2-38402 Drawing path3', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); let pathPoints : PointF[] = [new PointF(0, 0), new PointF(100, 0), new PointF(100, 100), new PointF(0, 100), new PointF(0, 0), new PointF(100, 100), new PointF(0, 100), new PointF(100, 0) ]; let pathTypes : number[] = [ 0, 1, 1, 129, 0, 1, 1, 1 ]; //Create new PDF path. let path : PdfPath = new PdfPath(pathPoints, pathTypes); //Draw PDF path to page. path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_EJ2_Path3.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path3.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-04: Drawing path', () => { it('-EJ2-38402 Drawing path4', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set pen let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); //Create new PDF path. let path : PdfPath = new PdfPath(pen); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); //Draw PDF path to page. path.draw(page1, new PointF(10, 10)); // document.save("EJ2_38402_draw_path4.pdf"); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path4.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-05: Drawing path', () => { it('-EJ2-38402 Drawing path5', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set brush let brush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); //Create new PDF path. let path : PdfPath = new PdfPath(brush); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); //Draw PDF path to page. path.draw(page1, new PointF(0, 0)); //document.save("EJ2_38402_draw_path5.pdf"); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path5.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-06: Drawing path', () => { it('-EJ2-38402 Drawing path6', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); // set brush let brush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); //Create new PDF path. let path : PdfPath = new PdfPath( brush, PdfFillMode.Alternate); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); //Draw PDF path to page. path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_draw_path6.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path6.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-07: Drawing path', () => { it('-EJ2-38402 Drawing path7', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); let pathPoints : PointF[] = [new PointF(0, 0), new PointF(100, 0), new PointF(100, 100), new PointF(0, 100), new PointF(0, 0), new PointF(100, 100), new PointF(0, 100), new PointF(100, 0) ]; let pathTypes : number[] = [ 0, 1, 1, 129, 0, 1, 1, 1 ]; // set pen let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); //Create new PDF path. let path : PdfPath = new PdfPath(pen, pathPoints, pathTypes); //Draw PDF path to page. path.draw(page1, new PointF(0, 0)); // save the document. // document.save('EJ2_38402_draw_path7.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path7.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-08: Drawing path', () => { it('-EJ2-38402 Drawing path8', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); let pathPoints : PointF[] = [new PointF(0, 0), new PointF(100, 0), new PointF(100, 100), new PointF(0, 100), new PointF(0, 0), new PointF(100, 100), new PointF(0, 100), new PointF(100, 0) ]; let pathTypes : number[] = [ 0, 1, 1, 129, 0, 1, 1, 1 ]; // set brush let brush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); //Create new PDF path. let path : PdfPath = new PdfPath(brush, PdfFillMode.Alternate, pathPoints, pathTypes); //Draw PDF path to page. path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_EJ2_Path8.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path8.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-09: Drawing path', () => { it('-EJ2-38402 Drawing path9', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); // set pen let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // set brush let brush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); //Create new PDF path. let path : PdfPath = new PdfPath(pen, brush, PdfFillMode.Alternate); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); //Draw PDF path to page. path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_draw_path9.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path9.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-10: Drawing path', () => { it('-EJ2-38402 Drawing path10', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Set the path fill mode. path.fillMode = PdfFillMode.Winding; //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_EJ2_Path10.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path10.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-11: Drawing path', () => { it('-EJ2-38402 Drawing path11', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Set the path fill mode. path.fillMode = PdfFillMode.Winding; //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); let pathPoints : PointF[] = path.pathPoints; //Get path point count. let count : number = path.pointCount; //Get last point let lastPoint : PointF = path.lastPoint; //Get last point. let lastPoint1 : PointF = path.getLastPoint(); path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_EJ2_Path11.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path11.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-12: Drawing path', () => { it('-EJ2-38402 Drawing path Arc', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Add arc. path.addArc(new RectangleF(0, 0, 100, 100), 0, -90); path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_Draw_PathArc.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_PathArc.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-13: Drawing path', () => { it('-EJ2-38402 Drawing path Arc1', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Add arc. path.addArc(0, 0, 100, 100, 0, -90); path.draw(page1, new PointF(0, 0)); // save the document. // document.save('EJ2_38402_Draw_PathArc1.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_PathArc1.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-14: Drawing path', () => { it('-EJ2-38402 Drawing path bezier', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Start figure. path.startFigure(); //Add bezier. path.addBezier(new PointF(30, 30), new PointF(90, 0), new PointF(60, 90), new PointF(120, 30)); //Close figure. path.closeFigure(); path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_Draw_PathBezier.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_PathBezier.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-15: Drawing path', () => { it('-EJ2-38402 Drawing path bezier1', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Start figure. path.startFigure(); //Add bezier. path.addBezier(30, 30, 90, 0, 60, 90, 120, 30); //Close figure. path.closeFigure(); path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_Draw_PathBezier1.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_PathBezier1.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-16: Drawing path', () => { it('-EJ2-38402 Drawing path Ellipse', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Add ellipse. path.addEllipse(new RectangleF(0, 0, 200, 100)); path.draw(page1, new PointF(0, 0)); // save the document. // document.save('EJ2_38402_Draw_PathEllipse.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_PathEllipse.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-17: Drawing path', () => { it('-EJ2-38402 Drawing path Ellipse1', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Add ellipse. path.addEllipse(0, 0, 200, 100); path.draw(page1, new PointF(0, 0)); // save the document. // document.save('EJ2_38402_Draw_PathEllipse1.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_PathEllipse1.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-18: Drawing path', () => { it('-EJ2-38402 Drawing path Lines1', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Add lines. path.addLine(10, 100, 10, 200); path.draw(page1, new PointF(0, 0)); // save the document. // document.save('EJ2_38402_Draw_PathLine1.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_PathLine1.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-19: Drawing path', () => { it('-EJ2-38402 Drawing Addpath', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); let pathPoints : PointF[] = [new PointF(0, 0), new PointF(100, 0), new PointF(100, 100), new PointF(0, 100), new PointF(0, 0), new PointF(100, 100), new PointF(0, 100), new PointF(100, 0) ]; let pathTypes : number[] = [ 0, 1, 1, 129, 0, 1, 1, 1 ]; //Create new PDF path. let ppath : PdfPath = new PdfPath(pathPoints, pathTypes); path.addPath(ppath); path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_Draw_Addpath.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_Addpath.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-20: Drawing path', () => { it('-EJ2-38402 Drawing Addpath1', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); let pathPoints : PointF[] = [new PointF(0, 0), new PointF(100, 0), new PointF(100, 100), new PointF(0, 100), new PointF(0, 0), new PointF(100, 100), new PointF(0, 100), new PointF(100, 0) ]; let pathTypes : number[] = [ 0, 1, 1, 129, 0, 1, 1, 1 ]; path.addPath(pathPoints, pathTypes); path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_Draw_Addpath1.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_Addpath1.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-21: Drawing path', () => { it('-EJ2-38402 Drawing AddPie', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); path.addPie(new RectangleF(20, 20, 70, 70), -45, 90); path.draw(page1, new PointF(0, 0)); // save the document. // document.save('EJ2_38402_Draw_AddPie.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_AddPie.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-22: Drawing path', () => { it('-EJ2-38402 Drawing AddPie', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); path.addPie(20, 20, 70, 70, -45, 90); path.draw(page1, new PointF(0, 0)); // save the document. // document.save('EJ2_38402_Draw_AddPie1.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_AddPie1.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-23: Drawing path', () => { it('-EJ2-38402 Drawing AddPolygon', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); let polygonPoints : PointF[] = [new PointF(23, 20), new PointF(40, 10), new PointF(57, 20), new PointF(50, 40), new PointF(30, 40) ]; //Add polygon. path.addPolygon(polygonPoints); path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_Draw_AddPolygon.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_AddPolygon.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-24: Drawing path', () => { it('-EJ2-38402 Drawing AddRectangle', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); path.addRectangle(new RectangleF(0, 0, 200, 100)); path.draw(page1, new PointF(0, 0)); // save the document. // document.save('EJ2_38402_Draw_AddRectangle.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_AddRectangle.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-25: Drawing path', () => { it('-EJ2-38402 Drawing AddRectangle1', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); path.addRectangle(0, 0, 200, 100); path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_Draw_AddRectangle1.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_AddRectangle1.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-26: Drawing path', () => { it('-EJ2-38402 Drawing start figure', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //First Start figure. path.startFigure(); //Add arc. path.addArc(10, 10, 50, 50, 0, 270); //Close figure. path.closeFigure(); //Second Start figure. path.startFigure(); //Add arc. path.addRectangle(10, 70, 50, 100); //Close figure. path.closeFigure(); path.draw(page1, new PointF(0, 0)); // save the document. // document.save('EJ2_38402_Draw_Path_startfigure.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_Path_startfigure.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-27: Drawing path', () => { it('-EJ2-38402 Drawing Close figure', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //First Start figure. path.startFigure(); //Add arc. path.addArc(10, 10, 50, 50, 0, 270); //Close figure. path.closeFigure(); //Second Start figure. path.startFigure(); //Add arc. path.addRectangle(10, 70, 50, 100); //Close figure. path.closeFigure(); path.draw(page1, new PointF(0, 0)); // save the document. // document.save('EJ2_38402_Draw_Path_Closefigure.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_Path_Closefigure.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-28: Drawing path', () => { it('-EJ2-38402 Drawing All Close figure', (done) => { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //First Start figure. path.startFigure(); path.addLine(new PointF(10, 100), new PointF(150, 100)); path.addLine(new PointF(150, 100), new PointF(10, 200)); path.startFigure(); //Add arc. path.addArc(200, 200, 100, 100, 0, 90); path.startFigure(); let point1 : PointF = new PointF(300, 300); let point2 : PointF = new PointF(400, 325); let point3 : PointF = new PointF(400, 375); let point4 : PointF = new PointF(300, 400); let points : PointF[] = [ point1, point2, point3, point4 ]; path.addPolygon(points); //Close figure. path.closeAllFigures(); //Second Start figure. path.startFigure(); //Add arc. path.addRectangle(10, 70, 50, 100); //Close figure. path.closeFigure(); path.draw(page1, new PointF(0, 0)); // save the document. //document.save('EJ2_38402_Draw_Path_AllClosefigure.pdf'); document.save().then((xlBlob: { blobData:Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_Draw_Path_AllClosefigure.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-29: Drawing path', () => { it('-EJ2-38402 Drawing path public method', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); //Draw PDF path to page. path.draw(page1, 10, 10); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path_public.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-30: Drawing path', () => { it('-EJ2-38402 Drawing path public method1', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); let rect : RectangleF = new RectangleF(20, 30, 100, 100); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); //Draw PDF path to page. path.draw(page1, rect); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path_public1.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-31: Drawing path', () => { it('-EJ2-38402 Drawing path public method2', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); let rect : RectangleF = new RectangleF(0, 0, 100, 100); let layoutFormat : PdfLayoutFormat = new PdfLayoutFormat(); layoutFormat.break = PdfLayoutBreakType.FitElement; layoutFormat.layout = PdfLayoutType.Paginate; layoutFormat.paginateBounds = new RectangleF(0, 0, 500, 350); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); //Draw PDF path to page. path.draw(page1, rect, layoutFormat); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path_public2.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-32: Drawing path', () => { it('-EJ2-38402 Drawing path public method3', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); let layoutFormat : PdfLayoutFormat = new PdfLayoutFormat(); layoutFormat.break = PdfLayoutBreakType.FitElement; layoutFormat.layout = PdfLayoutType.Paginate; layoutFormat.paginateBounds = new RectangleF(0, 0, 500, 350); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); //Draw PDF path to page. path.draw(page1, 10, 30, layoutFormat); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path_public3.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('UTC-33: Drawing path', () => { it('-EJ2-38402 Drawing path public method4', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); let layoutFormat : PdfLayoutFormat = new PdfLayoutFormat(); layoutFormat.break = PdfLayoutBreakType.FitElement; layoutFormat.layout = PdfLayoutType.Paginate; layoutFormat.paginateBounds = new RectangleF(0, 0, 500, 350); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); //Draw PDF path to page. path.draw(page1, new PointF(10, 30), layoutFormat); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38402_draw_path_public4.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); // destroy the document document.destroy(); }) }); describe('PdfPath.ts', () => { describe('Constructor initializing',()=> { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); //Create new PDF path. let path : PdfPath = new PdfPath(); let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); let brush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let pathPoints : PointF[] = [new PointF(0, 0), new PointF(100, 0), new PointF(100, 100), new PointF(0, 100), new PointF(0, 0), new PointF(100, 100), new PointF(0, 100), new PointF(100, 0) ]; let pathTypes : number[] = [ 0, 1, 1, 129, 0, 1 ]; //Create new PDF path. let ppath : PdfPath = new PdfPath(); it('-AddPath() method calling)', () => { expect(function (): void {path.addPath(null, null); }).toThrowError(); }) it('-AddPath() method calling1)', () => { expect(function (): void {path.addPath(pathPoints, null); }).toThrowError(); }) it('-AddPath() method calling2)', () => { expect(function (): void {path.addPath(pathPoints, pathTypes); }).toThrowError(); }) it('-AddPath() Draw graphics internal calling)', () => { expect(function (): void {path.drawInternal(null); }).toThrowError(); }) it('-AddPath() close figure calling)', () => { expect(function (): void {path.closeFigure(-1); }).toThrowError(); }) path.pen = pen; path.brush = brush; }) });
the_stack
import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, NgZone, OnDestroy, OnInit, ViewChild, } from '@angular/core' import Color from 'color' import {FlatTreeControl} from '@angular/cdk/tree' import {MatTreeFlatDataSource, MatTreeFlattener} from '@angular/material/tree' import {DataStore, DataStoreAutoCompleter} from '../data/data-store' import {BehaviorSubject, Subscription} from 'rxjs' import {MatDialog} from '@angular/material/dialog' import {ItemDetailsComponent} from '../item-details/item-details.component' import {DayID, Item, ItemID, ItemStatus} from '../data/common' import {debounceTime} from 'rxjs/operators' import {CdkVirtualScrollViewport} from '@angular/cdk/scrolling' import { ItemDroppedEvent, ItemDroppedInsertionType, } from '../item/item.component' import {DataAnalyzer, TaskProblemType} from '../data/data-analyzer' import {GotoItemComponent} from '../goto-item/goto-item.component' const SEARCH_IDLE_DELAY = 200 export interface ItemNode { problem?: TaskProblemType estimatedDoneDate?: DayID effectiveDeferDate?: DayID effectiveDueDate?: DayID expandable: boolean id: ItemID level: number name: string status: ItemStatus effectiveCost: number cost: number isIndirect: boolean color: Color canRepeat: boolean effectiveProgress: number } class ItemFilter { showCompleted = false showActive = true showDeferred = true searchQuery: string = '' autocompleter?: DataStoreAutoCompleter get isSearching() { return this.searchQuery !== '' } process(items: Item[], dataStore: DataStore): Item[] { const currentDate = dataStore.getCurrentDayID() if (!this.showCompleted) { items = items.filter(item => item.status !== ItemStatus.COMPLETED) } if (!this.showActive) { items = items.filter(item => item.status !== ItemStatus.ACTIVE) } if (!this.showDeferred) { // TODO optimize this items = items.filter(item => { const deferDate = dataStore.getEffectiveDeferDate(item) return deferDate === undefined || deferDate <= currentDate }) } if (this.autocompleter !== undefined && this.searchQuery !== '') { const resultIDs = new Set( this.autocompleter.queryIDs(this.searchQuery)) items = items.filter(item => resultIDs.has(item.id)) } return items } onDataStoreUpdated(dataStore: DataStore) { this.autocompleter = dataStore.createAutoCompleter() } } @Component({ selector: 'app-items', templateUrl: './items.component.html', styleUrls: ['./items.component.scss'], }) export class ItemsComponent implements OnInit, OnDestroy, AfterViewInit { @ViewChild('scrollViewport') scrollViewport?: CdkVirtualScrollViewport @ViewChild( 'scrollViewport', {read: ElementRef}) scrollViewportElement?: ElementRef itemHeight = 30 indentation: number = 20 filter: ItemFilter = new ItemFilter() allowedItemIDs = new Set<ItemID>() indirectAllowedItemIDs = new Set<ItemID>() private _getChildren = (node: Item) => { // NOTE: This will always return a new array, so we can directly modify // it const children = this.dataStore.getChildren(node) return children.filter(item => this.allowedItemIDs.has(item.id)) } private _transformer = (item: Item, level: number): ItemNode => { let hasAllowedChild = false const childrenIDs = item.childrenIDs const numChildren = childrenIDs.length for (let i = 0; i < numChildren; ++i) { if (this.allowedItemIDs.has(childrenIDs[i])) { hasAllowedChild = true break } } const tasks = this.dataAnalyzer.getTasks(item.id) const problems = this.dataAnalyzer.getTaskProblems(item.id) const firstTask = tasks === undefined ? undefined : tasks[0] const effectiveInfo = this.dataStore.getEffectiveInfo(item) return { problem: (problems !== undefined && problems.length > 0 && problems[0].task === firstTask) ? problems[0].type : undefined, estimatedDoneDate: this.dataAnalyzer.getEstimatedDoneDate(item.id), effectiveDeferDate: effectiveInfo.deferDate, effectiveDueDate: effectiveInfo.dueDate, expandable: hasAllowedChild, id: item.id, level: level, name: item.name, status: item.status, effectiveCost: item.effectiveCost, cost: item.cost, isIndirect: this.indirectAllowedItemIDs.has(item.id), color: this.dataStore.getItemColor(item), canRepeat: item.repeat !== undefined && !effectiveInfo.hasAncestorRepeat, effectiveProgress: this.dataAnalyzer.getEffectiveProgress( item.id) || 0, } } treeControl = new FlatTreeControl<ItemNode, ItemID>( node => node.level, node => node.expandable, { trackBy: (node) => node.id, }, ) treeFlattener = new MatTreeFlattener<Item, ItemNode, ItemID>( this._transformer, node => node.level, node => node.expandable, this._getChildren, ) dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener) private onDataChanged = (dataStore: DataStore) => { this.filter.onDataStoreUpdated(dataStore) this.refresh() } private onAnalyzerChanged = (dataAnalyzer: DataAnalyzer) => { // TODO implement me this.refresh() } private dataStoreChangeSubscription?: Subscription private dataAnalyzerChangeSubscription?: Subscription private searchQueryChangeSubscription?: Subscription private _searchQuery: string = '' private searchQueryValue = new BehaviorSubject<string>(this._searchQuery) constructor( private readonly changeDetectorRef: ChangeDetectorRef, private readonly dataStore: DataStore, private readonly dataAnalyzer: DataAnalyzer, private readonly dialog: MatDialog, private readonly zone: NgZone, ) { this.dataSource.data = [] } ngOnInit() { this.subscribeToData() this.searchQueryChangeSubscription = this.searchQueryValue.pipe( debounceTime(SEARCH_IDLE_DELAY), ).subscribe((value) => { this.filter.searchQuery = value this.refresh() }) } ngAfterViewInit() { } ngOnDestroy() { this.unsubscribeFromData() this.searchQueryChangeSubscription?.unsubscribe() this.searchQueryChangeSubscription = undefined } hasChild = (_: number, node: ItemNode) => node.expandable getPadding(node: ItemNode) { return this.treeControl.getLevel(node) * this.indentation + 'px' } get showCompleted() { return this.filter.showCompleted } set showCompleted(value: boolean) { this.filter.showCompleted = value this.refresh() } get showActive() { return this.filter.showActive } set showActive(value: boolean) { this.filter.showActive = value this.refresh() } get statusFilter() { if (this.filter.showActive) { if (this.filter.showCompleted) { return 'all' } else { return 'active' } } else { if (this.filter.showCompleted) { return 'completed' } else { return 'none' } } } set statusFilter(value: string) { this.filter.showActive = false this.filter.showCompleted = false if (value == 'all') { this.filter.showActive = true this.filter.showCompleted = true } else if (value == 'active') { this.filter.showActive = true } else if (value == 'completed') { this.filter.showCompleted = true } this.refresh() } get searchQuery() { return this._searchQuery } set searchQuery(value: string) { this._searchQuery = value this.searchQueryValue.next(value) } get showDeferred() { return this.filter.showDeferred } set showDeferred(value: boolean) { if (value === this.filter.showDeferred) return this.filter.showDeferred = value this.refresh() } newItem(parentID?: ItemID) { const dialogRef = this.dialog.open(ItemDetailsComponent, { width: ItemDetailsComponent.DIALOG_WIDTH, data: { initialParent: parentID, }, hasBackdrop: true, disableClose: false, autoFocus: false, }) dialogRef.afterClosed().subscribe(result => { }) } openDetails(id: ItemID) { const item = this.dataStore.getItem(id) if (item === undefined) return const dialogRef = this.dialog.open(ItemDetailsComponent, { width: ItemDetailsComponent.DIALOG_WIDTH, data: {item}, hasBackdrop: true, disableClose: false, autoFocus: false, }) dialogRef.afterClosed().subscribe(result => { }) } expandAll() { this.treeControl.expandAll() } collapseAll() { this.treeControl.collapseAll() } addChildItem(node: ItemNode) { this.newItem(node.id) } removeItem(node: ItemNode) { this.dataStore.removeItem(node.id) } /** * NOTE: The items tab must be open already */ locateNodeByID(itemID: ItemID) { const node = this.getNodeByID(itemID) if (node === undefined) return this.expandParents(node) // TODO This is a hack setTimeout(() => { const index = this.getDisplayIndex(node) || 0 this.scrollViewport?.scrollToIndex(index) }) } getNodeByID(itemID: ItemID) { const {treeControl} = this const dataNodes = treeControl.dataNodes const size = dataNodes.length for (let i = 0; i < size; ++i) { const dataNode = dataNodes[i] if (dataNode.id === itemID) { return dataNode } } return undefined } getDisplayIndex(node: ItemNode): number | undefined { const nodes = this.dataSource._expandedData.value const size = nodes.length const itemID = node.id for (let i = 0; i < size; ++i) { if (nodes[i].id === itemID) { return i } } return undefined } expandParents(node: ItemNode) { const parent = this.getParent(node) if (parent) { this.treeControl.expand(parent) this.expandParents(parent) } } getParent(node: ItemNode) { const {treeControl} = this const currentLevel = treeControl.getLevel(node) if (currentLevel < 1) { return null } const startIndex = treeControl.dataNodes.indexOf(node) - 1 for (let i = startIndex; i >= 0; i--) { const currentNode = treeControl.dataNodes[i] if (treeControl.getLevel(currentNode) < currentLevel) { return currentNode } } } updateAllowedItems() { const items: Item[] = [] this.dataStore.state.items.forEach((item) => { items.push(item) }) const allowedItems = this.filter.process(items, this.dataStore) this.allowedItemIDs = new Set(allowedItems.map(item => item.id)) this.indirectAllowedItemIDs = new Set() // If an item is allowed, its parents should too const size = allowedItems.length for (let i = 0; i < size; i++) { let parentID = allowedItems[i].parentID while (parentID !== undefined) { if (!this.allowedItemIDs.has(parentID)) { this.allowedItemIDs.add(parentID) this.indirectAllowedItemIDs.add(parentID) } const parent = this.dataStore.getItem(parentID) if (parent !== undefined) { parentID = parent.parentID } else { parentID = undefined } } } } private refresh() { this.updateAllowedItems() this.dataSource.data = this.dataStore.getRootItems() .filter(item => this.allowedItemIDs.has(item.id)) if (this.filter.isSearching) { this.treeControl.expandAll() } this.changeDetectorRef.detectChanges() } trackByFn(index, node: ItemNode) { return node.id } subscribeToData() { if (this.dataStoreChangeSubscription === undefined) { this.dataStoreChangeSubscription = this.dataStore.onChange.subscribe(this.onDataChanged) } if (this.dataAnalyzerChangeSubscription === undefined) { this.dataAnalyzerChangeSubscription = this.dataAnalyzer.onChange.subscribe(this.onAnalyzerChanged) } } unsubscribeFromData() { this.dataStoreChangeSubscription?.unsubscribe() this.dataStoreChangeSubscription = undefined this.dataAnalyzerChangeSubscription?.unsubscribe() this.dataAnalyzerChangeSubscription = undefined } /** * Will be called when this as a tab is selected */ onActivate() { this.subscribeToData() // This forces the virtual scroll to redraw const el = this.scrollViewportElement?.nativeElement el?.dispatchEvent(new Event('scroll')) } /** * Will be called when another tab is selected */ onDeactivate() { this.unsubscribeFromData() } onNodeDragStart(node: ItemNode, event: DragEvent) { this.treeControl.collapse(node) event.dataTransfer?.setData('text', 'itemID ' + node.id.toString()) } onItemDropped(event: ItemDroppedEvent) { const {draggedItemID, receiverItemID, insertionType} = event if (insertionType === ItemDroppedInsertionType.CHILD) { if (!this.dataStore.canBeParentOf( draggedItemID, receiverItemID)) { return } const item = this.dataStore.getItem(draggedItemID) if (item !== undefined) { const draft = item.toDraft() draft.parentID = receiverItemID this.dataStore.updateItem(draft) } } else { if (draggedItemID === receiverItemID) return const parentID = this.dataStore.getItem(receiverItemID)?.parentID const item = this.dataStore.getItem(draggedItemID) if (item !== undefined) { const draft = item.toDraft() const insert = insertionType === ItemDroppedInsertionType.BELOW ? 'below' : 'above' draft.parentID = parentID this.dataStore.updateItem( draft, {anchor: receiverItemID, insert}) } } } gotoItem() { const dialogRef = this.dialog.open(GotoItemComponent, { width: GotoItemComponent.DIALOG_WIDTH, data: {}, hasBackdrop: true, disableClose: false, autoFocus: false, }) dialogRef.afterClosed().subscribe(result => { if (result !== undefined) { this.locateNodeByID(result) } }) } }
the_stack
import { generateId } from '@/common/js/util'; import { validateRules } from '@/common/js/validate'; import customRender from '@/components/customrender/bkDataCustomRender'; import popContainer from '@/components/popContainer'; import { Component, Emit, Prop, PropSync, Ref, Vue, Watch } from 'vue-property-decorator'; import { CreateElement, VNode } from 'vue/types/umd'; import { getFieldContraintConfigs, getFieldTypeConfig, getMasterTableInfo, updateMasterTableInfo, } from '../../Api/index'; import { IUpdateEvent, TabItem } from '../../Controller/DataModelTabManage'; import { CDataModelManage, MasterTableInfo, MstTbField } from '../../Controller/MasterTable'; import { IDataModelManage, IMasterTableInfo } from '../../Interface/index'; import { DragTable, DragTableColumn, DragTableRow } from '../DragTable/index'; import ExtendRows from './ChildNodes/ExtendRows'; import { FieldProcessingLogic, LoadRTTable, ReferDimensionTable } from './ChildNodes/index'; import { DataModelManage, IStepsManage } from './IStepsManage'; import { ConditionSelector } from '../Common/index'; import { debounce } from '@/common/js/util.js'; interface IColumn { /** 列显示 */ label: string; /** 对应字段名称 */ props: string; /** 是否必填 */ require: boolean; /** 列宽 */ width: string; /** 输入框宽度 */ inputWidth: number; /** 渲染函数 */ renderFn: () => {}; /** 校验配置 */ validate?: any[]; /** 输入框placeholder */ placeholder?: string; } const __time__ = { name: '__time__', uid: generateId('__time__'), }; Vue.component('ConditionSelector', ConditionSelector); @Component({ components: { DragTableColumn, DragTable, DragTableRow, FieldProcessingLogic, LoadRTTable, ReferDimensionTable, ExtendRows, customRender, popContainer, }, }) export default class MainTableDesign extends DataModelManage.IStepsManage { get activeModelTabItem() { return this.DataModelTabManage.getActiveItem()[0]; } get tableList() { return this.masterTableInfo.fields .filter(item => !item.isExtendedField) .map(field => Object.assign({}, field, { isDrag: field.fieldName !== __time__.name, extends: this.masterTableInfo.fields.filter(f => f.joinFieldUId === field.uid), }) ); } get tableData() { return { columns: this.columns, list: this.tableList, }; } set tableData(val: any) { Object.assign(this.columns, val.columns); } get widthNum() { return this.offsetWidth / this.tableData.columns.length + 'px'; } /** 是否为维度表 */ get isDimension() { // 'dimension' : 'fact' return /^dimension/.test(this.activeModelTabItem.modelType); } /** 字段类型 */ get fieldCategoryList() { return [ { id: 'measure', name: '度量', disabled: this.isDimension }, { id: 'dimension', name: '维度', disabled: false }, ]; } /** 数据类型 */ get fieldTypeList() { return this.mFieldTypeList; } set fieldTypeList(val) { this.$set(this, 'mFieldTypeList', val); } get columns(): IColumn[] { return [ { label: '字段名', props: 'fieldName', placeholder: this.$t('由英文字母_下划线和数字组成_且字母开头'), require: true, width: '200px', renderFn: this.renderFieldNameColumn, validate: [ { require: true, }, { regExp: /^[a-zA-Z][a-zA-Z0-9_]*$/, error: this.$t('格式不正确_内容由字母_数字和下划线组成_且以字母开头'), }, { customValidateFun: this.validateFieldNameIsInner, error: this.$t('该名称为系统内置,请修改名称'), }, { customValidateFun: this.validateFieldNameRepeated, error: this.$t('字段名重复'), }, ], }, { label: '字段中文名', props: 'fieldAlias', require: true, renderFn: () => this.renderFieldNameColumn.call(this, ...arguments, false), validate: [{ require: true }], }, { label: '数据类型', props: 'fieldType', require: true, renderFn: () => this.renderSelectColumn.call(this, ...arguments, this.fieldTypeList), validate: [{ require: true }], }, { label: '字段角色', props: 'fieldCategory', require: true, renderFn: () => this.renderSelectColumn.call(this, ...arguments, this.fieldCategoryList), validate: [{ require: true }], }, { label: '字段描述', props: 'description', require: false, width: '270px', renderFn: this.renderDescriptionColumn, }, { label: '值约束', props: 'fieldConstraintContent', require: false, width: '400px', renderFn: this.renderValueConstraintColumn, }, { label: '字段加工逻辑', props: 'fieldCleanContent', require: false, renderFn: this.renderClearColumn, }, { label: '主键', props: 'isPrimaryKey', require: false, width: '100px', renderFn: this.renderPrimaryKeyCheckbox, }, { label: '操作', props: 'operating', require: false, width: '100px', renderFn: this.renderOptionColumn, }, ]; } get fieldsWithoutTimeField() { return this.masterTableInfo.fields.filter(f => f.fieldName !== __time__.name); } get canAssociationDimension() { return !this.fieldsWithoutTimeField.filter(item => item.fieldName).length; } /** 字段约束配置列表 */ public fieldConstraintConfig: IDataModelManage.IFieldContraintConfig[] = []; /** 表单验证 */ public validateResult = { isSuccess: true, }; /** 时间字段 */ public timeField = new CDataModelManage.MstTbField({ fieldName: __time__.name, fieldAlias: '时间字段', fieldType: 'timestamp', fieldCategory: 'dimension', description: '平台内置时间字段,数据入库后将转换为可查询字段,比如 dtEventTime、dtEventTimeStamp、localtime', uid: __time__.uid, }); /** 主表数据 */ public masterTableInfo: IDataModelManage.IMasterTableInfo = new CDataModelManage.MasterTableInfo({ modelId: 0, fields: [new CDataModelManage.MstTbField({})], modelRelation: [], }); public isLocalLoading = false; public offsetWidth = 0; public observer = null; /** 加载结果表的结构侧栏弹出 */ public isLoadRtTableSliderShow = false; /** 关联维度表数据模型Z弹出 */ public isReferDimensionTableShow = false; /** 关联维度表数据模型Z 新建/编辑状态 */ public isReferDimensionTableEdit = false; /** 字段加工逻辑侧栏信息 */ public fieldProcessingLogicSlider: object = { isShow: false, title: '', editable: true, field: new CDataModelManage.MstTbField({}), }; public relatedField: IDataModelManage.IMasterTableField = {}; /** 当前操作行 */ public activeFieldItem = { index: -1, columnIndex: -1, item: {}, }; public validatorMap = { number: { validator: function (val) { return !isNaN(Number(val)); }, message: window.$t('请输入数字'), trigger: 'blur', }, regex: { validator: function (val) { return /^\/.+\/[gimsuy]*$/.test(val); }, message: window.$t('请输入正确的正则'), trigger: 'blur', }, required: { required: true, message: window.$t('不能为空'), trigger: 'blur', }, }; private mFieldTypeList = []; /** 内置字段 */ public innerFieldList = [ 'timestamp', 'offset', 'bkdata_par_offset', 'dtEventTime', 'dtEventTimeStamp', 'localTime', 'thedate', 'rowtime', ]; /** * 渲染字段名称列 * @param h * @param column * @param row * @param index * @param isFirstColumn 是否是首列 */ public renderFieldNameColumn( h: CreateElement, column: IColumn, row: IDataModelManage.IMasterTableField, rowIndex: number, columnIndex: number, isFirstColumn = true ) { const fieldName = this.getFieldName(row.fieldName); let isValidateFailed = this.validateResult[fieldName] && this.validateResult[fieldName][column.props] && this.validateResult[fieldName][column.props].visible; /** 当校验结果为失败时,重新校正校验结果,同一个字段会存在重复和不为空两种校验 */ if (isValidateFailed) { isValidateFailed = !validateRules(column.validate, row[column.props], {}); } if (this.isSystemTimeField(row) || row.isExtendedField) { const showValue = row[column.props] === __time__.name ? '--' : row[column.props]; return this.renderText(h, showValue, { class: ['row-column-container text', column.props === 'fieldName' ? 'offset-left13' : ''], style: { color: '#63656e' }, directives: [ { name: 'bk-tooltips', value: { content: column.props === 'fieldAlias' && row.fieldName === __time__.name && this.isDimension ? this.$t( '时间字段,当用户在选择该字段后,在模型被实例化时,由系统按计算' + '类型自动添加相应的时间字段,否则没有' ) : showValue, interactive: false, }, }, ], }); } // 限制修改fieldName const self = this; if (column.props === 'fieldName' && row.editable === false) { return h( 'span', { class: ['row-column-container text', column.props === 'fieldName' ? 'offset-left13' : ''], }, [ row.isJoinField && isFirstColumn ? h( 'i', { class: 'bk-icon icon-left-join column-icon join-field-icon', }, '' ) : '', self.renderText(h, row[column.props], { style: { color: '#63656e', display: 'block' }, directives: [ { name: 'bk-tooltips', value: { content: ` <p>字段名:${row[column.props]}</p> <p>该字段无法修改,原因如下:</p> ${self.getFieldEditableInfo(row.editableDeletableInfo, 'edit')} `, interactive: false, }, }, ], }), ] ); } return this.renderValidateColumn( h, column, row, rowIndex, columnIndex, [ row.isJoinField && isFirstColumn ? h( 'i', { class: 'bk-icon icon-left-join column-icon join-field-icon', }, '' ) : '', this.renderInputColumn(h, column, row, rowIndex), ], [column.props === 'fieldName' ? 'offset-left13' : ''] ); } /** * 渲染操作列 * @param h * @param column * @param row * @param rowIndex * @param columnIndex */ public renderOptionColumn( h: CreateElement, column: IColumn, row: IDataModelManage.IMasterTableField, rowIndex: number, columnIndex: number ) { const showIcons = !this.isSystemTimeField(row); /** 是否渲染时间字段操作项 */ const showTimeOpt = this.isSystemTimeField(row) && this.isDimension; /** 维度表:选择是否添加时间字段 */ const timeFieldOpt = showTimeOpt ? h('bkdata-switcher', { props: { theme: 'primary', value: !row._disabled, }, class: 'opt-icon', on: { change: this.handleTimeFieldActive, }, }) : ''; const joinFieldOpt = showIcons && row.isJoinField && !row.isExtendedField ? (() => { // 根据草稿态关联维度表状态设置按钮 const extendFields = row['extends'] || []; const hasError = !extendFields.every(field => field.fieldType && field.fieldCategory); const relation = this.masterTableInfo.modelRelation .find(relation => relation.fieldName === row.fieldName) || {}; const { relatedModelActiveStatus, relatedModelName } = relation; const isRelatedDimensionDelete = relatedModelActiveStatus === 'disabled'; const tipsContent = !isRelatedDimensionDelete ? this.$t(`当前被关联的维度表(${relatedModelName})已更新,请重新配置`) : this.$t(`当前被关联的维度表(${relatedModelName})已被删除,请重新配置`); return h('i', { class: 'bk-icon icon-icon-set-fill opt-icon' + (hasError || isRelatedDimensionDelete ? ' error' : ''), directives: [ { name: 'bk-tooltips', value: { content: hasError || isRelatedDimensionDelete ? tipsContent : this.$t('关联维度表数据模型设置'), interactive: false, }, }, ], on: { click: () => this.handleEditDimensionField(row, rowIndex), }, }); })() : ''; const plusOpt = row.isExtendedField || !showIcons ? '' : h('i', { class: 'bk-icon icon-plus-9 opt-icon', on: { click: () => this.handleAppendRow(row, rowIndex), }, }); let minusOpt = ''; const self = this; if (row.isExtendedField || this.fieldsWithoutTimeField.length <= 1 || !showIcons) { minusOpt = ''; } else if (row.deletable === false) { minusOpt = h('i', { class: 'bk-icon icon-minus-6 opt-icon', style: { cursor: 'not-allowed' }, directives: [ { name: 'bk-tooltips', value: { content: self.getFieldEditableInfo(row.editableDeletableInfo, 'delete'), interactive: false, }, }, ], }); } else { minusOpt = h('i', { class: 'bk-icon icon-minus-6 opt-icon', on: { click: () => this.handleRemoveRow(row, rowIndex), }, }); } return h('span', { class: 'icon-group' }, [plusOpt, minusOpt, joinFieldOpt, timeFieldOpt]); } /** * 渲染TagInput * 暂时不用,实现字段推荐时在启用 * @param h * @param column * @param row * @param index */ public renderTagInputColumn( h: CreateElement, column: IColumn, row: IDataModelManage.IMasterTableField, index: number ) { return h('bkdata-tag-input', { domProps: { list: [], 'allow-next-focus': false, 'allow-create': true, 'allow-auto-match': true, }, }); } /** * 渲染Input输入框 * @param h * @param column * @param row * @param rowIndex * @param columnIndex */ public renderInputColumn( h: CreateElement, column: IColumn, row: IDataModelManage.IMasterTableField, rowIndex: number, columnIndex: number ) { const self = this; return h('bkdata-input', { props: { value: row[column.props], placeholder: column.placeholder, }, directives: [ { name: 'bk-tooltips', value: { content: row[column.props], interactive: false, disabled: !row[column.props], }, }, ], on: { blur(value) { const targetIndex = self.masterTableInfo.fields.findIndex( item => (row.id && item.id === row.id) || (row.uid && item.uid === row.uid) ); if (targetIndex >= 0) { const targetField = self.masterTableInfo.fields[targetIndex]; targetField[column.props] = value; self.masterTableInfo.fields.splice(targetIndex, 1, targetField); self.handleFormDataChanged(); if (column.validate) { self.validateFormItem(targetField.fieldName, column.props, value, column.validate, true); } } }, }, }); } /** * 渲染带有校验的列 * @param h * @param column * @param row * @param rowIndex * @param columnIndex * @param insertColumns */ public renderValidateColumn( h: CreateElement, column: IColumn, row: IDataModelManage.IMasterTableField, rowIndex: number, columnIndex: number, insertColumns: any[], cls: string[] = [] ) { const self = this; const fieldName = this.getFieldName(row.fieldName); let isValidateFailed = this.validateResult[fieldName] && this.validateResult[fieldName][column.props] && this.validateResult[fieldName][column.props].visible; /** 当校验结果为失败时,重新校正校验结果,同一个字段会存在重复和不为空两种校验 */ if (isValidateFailed) { isValidateFailed = !validateRules(column.validate, row[column.props], {}); } return h('span', { class: ['row-column-container', ...cls, isValidateFailed && 'is-validate-fail'] }, [ ...insertColumns, isValidateFailed ? h('i', { class: 'validate-msg-icon icon icon-exclamation-circle-shape', directives: [ { name: 'bk-tooltips', value: this.validateResult[fieldName][column.props].content, }, ], }) : '', ]); } /** * 渲染下拉列表组件 * @param h * @param column * @param row * @param rowIndex * @param columnIndex * @param listOptions */ public renderSelectColumn( h: CreateElement, column: IColumn, row: IDataModelManage.IMasterTableField, rowIndex: number, columnIndex: number, listOptions: any[] ) { const iconMap = { measure: 'icon-measure-line', dimension: 'icon-dimens', }; const self = this; if (this.isSystemTimeField(row)) { return this.renderText(h, '--', { class: 'row-column-container text' }); } if (row.isExtendedField) { const option = listOptions.find(item => item.id === row[column.props]); let text = ''; if (option) { text = option.name || '--'; if (column.props === 'fieldCategory' && text !== '--') { text = [ h( 'i', { class: iconMap[option.id], style: { fontSize: '14px', color: '#C4C6CC', marginRight: '5px', }, }, '' ), h('span', {}, text), ]; } } return this.renderText(h, text, { class: 'row-column-container text', style: { color: '#63656e' }, }); } if (column.props === 'fieldType' && row.editableFieldType === false) { const option = listOptions.find(item => item.id === row[column.props]); const text = option?.name || '--'; return this.renderText(h, text, { class: 'row-column-container text', style: { color: '#63656e' }, directives: [ { name: 'bk-tooltips', value: { content: self.getFieldEditableInfo(row.editableDeletableInfo, 'edit'), interactive: false, }, }, ], }); } return this.renderValidateColumn(h, column, row, rowIndex, columnIndex, [ column.props === 'fieldCategory' && h('i', { class: `${iconMap[row[column.props]]} category-icon` }, ''), h( 'bkdata-select', { class: column.props === 'fieldCategory' && 'category-selector', props: { value: row[column.props], clearable: false, }, on: { change(value) { if (rowIndex >= 0) { const targetField = self.masterTableInfo.fields[rowIndex]; targetField[column.props] = value; self.masterTableInfo.fields.splice(rowIndex, 1, targetField); self.handleFormDataChanged(); if (column.validate) { self.validateFormItem(targetField.fieldName, column.props, value, column.validate, true); } } }, }, }, listOptions.map(item => h( 'bkdata-option', { props: { key: item.id, id: item.id, name: item.name, disabled: item.disabled, }, }, [ h( 'i', { class: iconMap[item.id], style: { fontSize: '14px', color: '#C4C6CC', marginRight: '5px', }, }, '' ), h('span', {}, item.name), ] ) ) ), ]); } /** * 字段描述 * @param h * @param column * @param row * @param rowIndex * @param columnIndex */ public renderDescriptionColumn( h: CreateElement, column: IColumn, row: IDataModelManage.IMasterTableField, rowIndex: number, columnIndex: number ) { return this.isSystemTimeField(row) ? this.renderText(h, row[column.props], { class: 'row-column-container text', directives: [ { name: 'bk-tooltips', value: { content: row[column.props] || '', interactive: false, }, }, ], }) : this.renderInputColumn(h, column, row, rowIndex, columnIndex); } /** * 渲染纯文本 * @param h * @param column * @param row */ public renderText(h: CreateElement, text: string, options: any = {}) { return h( 'span', { ...options, }, text ); } /** * 字段加工逻辑列渲染 * @param h * @param column * @param row */ public renderClearColumn( h: CreateElement, column: IColumn, row: IDataModelManage.IMasterTableField, rowIndex: number, columnIndex: number ) { const fieldCleanContent = (row[column.props] || {}).cleanOption || this.$t('未设置'); const self = this; if (this.isSystemTimeField(row) || row.isExtendedField) { return this.renderText(h, '--', { class: 'row-column-container text', style: { color: '#63656e' }, }); } return this.renderText(h, fieldCleanContent, { on: { click: () => { self.activeFieldItem.columnIndex = columnIndex; self.handleFieldProcessingLogic(row, row.isExtendedField); self.sendUserActionData({ name: '点击【字段加工逻辑】' }); }, }, style: { color: (row[column.props] || {}).cleanOption ? '#3a84ff' : '#c4c6cc', }, class: ['field-clean-type pointer-cell', { selected: self.activeFieldItem.columnIndex === columnIndex }], }); } /** * 渲染值约束列 * @param h * @param column * @param row * @param options */ public renderValueConstraintColumn( h: CreateElement, column: IColumn, row: IDataModelManage.IMasterTableField, rowIndex: number, columnIndex: number ) { const self = this; if (this.isSystemTimeField(row) || (!row[column.props] && row.isExtendedField)) { return this.renderText(h, '--', { class: 'row-column-container text', style: { color: '#63656e' } }); } return h('condition-selector', { props: { constraintList: self.fieldConstraintConfig .filter(cfg => cfg.allowFieldType.some(t => t === row.fieldType)), constraintContent: row[column.props], readonly: row.isExtendedField, fieldDisplayName: `${row.fieldName} (${row.fieldAlias})`, }, on: { change(content: object | null) { const targetIndex = self.masterTableInfo.fields.findIndex(item => row.uid && item.uid === row.uid); if (targetIndex >= 0) { const field = self.masterTableInfo.fields[targetIndex]; field[column.props] = content; self.masterTableInfo.fields.splice(targetIndex, 1, field); } self.sendUserActionData({ name: '确定【值约束】' }); self.handleFormDataChanged(); }, click() { !row.isExtendedField && self.sendUserActionData({ name: '点击【值约束】' }); }, }, }); } /** * 渲染主键checkbox * @param h * @param column * @param row * @param rowIndex * @param columnIndex */ public renderPrimaryKeyCheckbox( h: CreateElement, column: IColumn, row: IDataModelManage.IMasterTableField, rowIndex: number, columnIndex: number ) { const self = this; const config = { class: 'row-column-container text', style: { color: '#63656e' }, }; if (this.isSystemTimeField(row) || row.isExtendedField) { return this.renderText(h, '--', config); } if (row.fieldCategory !== 'dimension') { const target = self.masterTableInfo.fields.find( item => (row.id && item.id === row.id) || (row.uid && item.uid === row.uid) ); if (target) { target[column.props] = false; } return h('bkdata-checkbox', { props: { value: false, disabled: true, }, style: { marginRight: 0, marginLeft: '6px', }, directives: [ { name: 'bk-tooltips', value: { content: '只能将字段角色为维度的字段设置为主键', interactive: false, }, }, ], }); } return h('bkdata-checkbox', { props: { value: row[column.props], }, style: { marginRight: 0, marginLeft: '6px', }, on: { change(value) { let hasChange = false; self.masterTableInfo.fields.forEach((item, index) => { if (item.isPrimaryKey) { item[column.props] = false; hasChange = true; } if ((row.id && item.id === row.id) || (row.uid && item.uid === row.uid)) { item[column.props] = value; hasChange = true; } }); hasChange && self.handleFormDataChanged(); }, }, }); } public isSystemTimeField(row: any = {}) { return row.uid === __time__.uid && !row.isFromRt; } /** 表单数据被修改之后,设置上一步、下一步需要二次弹窗确认 */ public handleFormDataChanged() { this.syncPreNextBtnManage.isPreNextBtnConfirm = true; } /** * 计算列宽度 * @param col */ public getColumnsWidth(col) { return col.width || this.widthNum; } /** 拉取主表信息 */ public loadMasterTableInfo() { this.isLocalLoading = true; Promise.all([ getFieldTypeConfig(), getMasterTableInfo(this.modelId, true, undefined, ['editable', 'deletable']), getFieldContraintConfigs(), ]) .then(res => { const fieldType = res[0]; const tableInfo = res[1]; const fieldContraintConfigs = res[2]; fieldType.setDataFn(data => { this.fieldTypeList = (data || []) .map(d => Object.assign({}, { name: d.field_type, id: d.field_type })); }); /** 字段约束配置列表 */ fieldContraintConfigs.setData(this, 'fieldConstraintConfig'); this.$nextTick(() => { tableInfo.setDataFn(data => { // 补齐 editableDeletableInfo fields、isExtendedFieldDeletableEditable for (const field of data.fields) { if (!field.editableDeletableInfo.hasOwnProperty('fields')) { field.editableDeletableInfo.fields = []; } if (!field.editableDeletableInfo.hasOwnProperty('isExtendedFieldDeletableEditable')) { field.editableDeletableInfo.isExtendedFieldDeletableEditable = true; } } this.masterTableInfo = data; // 关闭time字段后,下次进入主表补齐time字段 const timeFieldIndex = this.masterTableInfo.fields .findIndex(field => field.fieldName === __time__.name); if (this.masterTableInfo.fields.length && timeFieldIndex === -1) { this.masterTableInfo.fields.push(Object.assign({}, this.timeField, { _disabled: true })); } else if (timeFieldIndex >= 0) { this.masterTableInfo.fields.splice( timeFieldIndex, 1, Object.assign({}, this.masterTableInfo.fields[timeFieldIndex], { _disabled: false }) ); } this.masterTableInfo.fields.sort((a, b) => { if (this.isSystemTimeField(a)) { return 1; } else if (this.isSystemTimeField(b)) { return -1; } return a.isExtendedField - b.isExtendedField; }); // 前端维护uid const nameMap = {}; for (const field of this.masterTableInfo.fields) { nameMap[field.fieldName] = field; if (field.fieldName === __time__.name) { !field.uid && (field.uid = __time__.uid); continue; } Object.assign(field, { uid: generateId('__mst_rt_field_id_') }); } // 添加关联唯一标识joinFieldUId this.masterTableInfo.fields.forEach(field => { if (field.joinFieldName && nameMap[field.joinFieldName]) { Object.assign(field, { joinFieldUId: nameMap[field.joinFieldName].uid }); } }); // 关联关系添加唯一标识uid this.masterTableInfo.modelRelation.forEach(relation => { if (relation.fieldName && nameMap[relation.fieldName]) { Object.assign(relation, { joinFieldUId: nameMap[relation.fieldName].uid }); } }); }); this.initDefaultField(); }); }) ['finally'](() => { this.isLocalLoading = false; }); } /** 新增主表时默认初始化一行数据 */ public initDefaultField() { const defaultField = new CDataModelManage.MstTbField({}); this.isDimension && Object.assign(defaultField, { fieldCategory: 'dimension' }); const timeField = Object.assign({}, this.timeField, { _disabled: false }); if (!this.masterTableInfo) { this.masterTableInfo = new CDataModelManage.MasterTableInfo({ modelId: this.modelId, fields: [defaultField, timeField], modelRelation: [], }); } if (!this.masterTableInfo.fields || !this.masterTableInfo.fields.length) { this.masterTableInfo.fields = [defaultField, timeField]; } } /** * 处理字段为空的情况 * @param fieldName */ public getFieldName(fieldName: string) { if (/^\s*$/.test(fieldName)) { fieldName = '__empty__'; } return fieldName; } /** * 校验字段是否符合提交规范 * @param fieldName 字段名称 * @param value 字段值 * @param regs 校验规则 * @param resetFieldName 是否重置本字段的校验 */ public validateFormItem(fieldName, columnName, value, regs, resetFieldName = false): boolean { fieldName = this.getFieldName(fieldName); if (!this.validateResult[fieldName] || resetFieldName) { this.validateResult[fieldName] = {}; } if (!this.validateResult[fieldName][columnName]) { this.validateResult[fieldName][columnName] = {}; } const result = validateRules(regs, value, this.validateResult[fieldName][columnName]); if (this.validateResult.isSuccess) { this.validateResult.isSuccess = result; } return result; } /** * 校验全部数据是否合法 */ public validateFormItems() { this.validateResult = { isSuccess: true }; this.masterTableInfo.fields.forEach(field => { this.columns.forEach(column => { // 内置字段不需要校验 if (column.validate && field.uid !== __time__.uid) { this.validateFormItem(field.fieldName, column.props, field[column.props], column.validate); } }); }); return Promise.resolve(this.validateResult.isSuccess); } /** * 校验主表字段是否合法(不包括扩展字段) */ public validateMainFormItems() { this.validateResult = { isSuccess: true }; this.masterTableInfo.fields .filter(field => !field.isExtendedField && field.uid !== __time__.uid) .forEach(field => { this.columns.forEach(column => { if (column.validate) { this.validateFormItem(field.fieldName, column.props, field[column.props], column.validate); } }); }); return Promise.resolve(this.validateResult.isSuccess); } /** * 校验字段名称是否重复 * @param fieldName */ public validateFieldNameRepeated(fieldName: string) { return this.masterTableInfo.fields.filter(item => item.fieldName === fieldName).length <= 1; } /** * 校验字段名称是否为系统内置 * @param fieldName */ public validateFieldNameIsInner(fieldName: string) { return !this.innerFieldList.includes(fieldName.toLocaleLowerCase()); } /** * 激活时间字段 * @param isEnabled */ public handleTimeFieldActive(isEnabled: boolean) { const timefield = this.masterTableInfo.fields.find(item => item.fieldName === this.timeField.fieldName); if (timefield) { Object.assign(timefield, { _disabled: !isEnabled }); } } /** * 点击一行操作 * @param row * @param rowIndex */ public handleRowClick(row: IDataModelManage.IMasterTableField, rowIndex: number, columnIndex?: number) { this.activeFieldItem.index = rowIndex; this.activeFieldItem.item = row; this.activeFieldItem.columnIndex = columnIndex === undefined ? -1 : columnIndex; } /** * 行数据拖拽结束 * @param args 参数: args[0]:List, args[1]: CustomEvent */ public handleDragEnd(args: any[]) { const targetList = args[0] || []; const evts = args[1]; const { oldIndex, newIndex } = evts; /** * 表格渲染的数据tableList是重新计算的数据结构 * 和原始数据 masterTableInfo.fields 是有出入的 * 此处行的拖拽需要计算原始数据行位置 **/ const computedOldItem = this.tableList[oldIndex]; const computedNewItem = targetList[newIndex]; /** 计算拖拽的行在原始数据中的位置 */ const sourceOldIndex = this.masterTableInfo.fields.findIndex( field => field.fieldName === computedOldItem.fieldName ); const sourceOldItem = this.masterTableInfo.fields[sourceOldIndex]; /** 根据计算结果重置原始数据 */ this.masterTableInfo.fields.splice(sourceOldIndex, 1); this.masterTableInfo.fields.splice(newIndex, 0, sourceOldItem); /** 更新缓存:当前激活行 */ if (this.activeFieldItem.index >= 0) { const activeIndex = newIndex; this.handleRowClick(this.tableList[activeIndex], activeIndex); this.handleFormDataChanged(); } } /** * 移除字段设置 * @param field 字段设置 * @param index 字段Index */ public handleRemoveRow(field: IDataModelManage.IMasterTableField, rowIndex: number) { if (this.masterTableInfo.fields[rowIndex] && this.fieldsWithoutTimeField.length > 1) { const deleteFields = this.masterTableInfo.fields.splice(rowIndex, 1); if (deleteFields[0] && deleteFields[0].isJoinField) { const fieldIndex = this.masterTableInfo.modelRelation.findIndex( item => item.joinFieldUId === deleteFields[0].uid ); fieldIndex > -1 && this.masterTableInfo.modelRelation.splice(fieldIndex, 1); // 删除关联字段 for (let i = this.masterTableInfo.fields.length - 1; i >= 0; i--) { if (this.masterTableInfo.fields[i].joinFieldUId === deleteFields[0].uid) { this.masterTableInfo.fields.splice(i, 1); } } } // 更新编辑/删除限制 for (const fieldItem of this.masterTableInfo.fields) { const editableDeletableInfo = fieldItem.editableDeletableInfo || {}; const limitFields = editableDeletableInfo.fields || []; const limitFieldMap = {}; for (const item of limitFields) { limitFieldMap[item.fieldName] = item.fieldName; } if (limitFieldMap[deleteFields[0].fieldName]) { const newLimitFields = [...limitFields .filter(item => item.fieldName !== deleteFields[0].fieldName)]; fieldItem.editableDeletableInfo = Object.assign({}, editableDeletableInfo, { fields: newLimitFields, isUsedByOtherFields: !!newLimitFields.length, }); } const { deletable, editable } = this.getFieldLimit(fieldItem.editableDeletableInfo); fieldItem.deletable = deletable; fieldItem.editable = editable; } this.handleUpdateExtendedFieldLimit(); this.handleFormDataChanged(); } } /** * 从当前位置追加一行 * @param field * @param rowInde */ public handleAppendRow(field: IDataModelManage.IMasterTableField, rowInde: number) { const appendRowIndex = rowInde + 1; const newField = new CDataModelManage.MstTbField(); this.isDimension && Object.assign(newField, { fieldCategory: 'dimension' }); this.masterTableInfo.fields.splice(appendRowIndex, 0, newField); /** 激活新增行 */ this.handleRowClick(this.masterTableInfo.fields[appendRowIndex], appendRowIndex); } /** * 拉取主表数据 */ public handleLoadRtTable() { this.isLoadRtTableSliderShow = true; this.sendUserActionData({ name: '点击【加载结果表的结构】' }); } /** * 点击关联维度表数据模型弹出侧栏 */ public async handleReferDimensionTable() { if (this.canAssociationDimension || !(await this.validateMainFormItems())) { const message = this.canAssociationDimension ? '空表不能进行关联操作' : '请先处理表内错误'; this.$bkMessage({ theme: 'warning', message: this.$t(message), }); return; } this.isReferDimensionTableEdit = false; this.isReferDimensionTableShow = true; this.sendUserActionData({ name: '点击【关联维度表数据模型】' }); } /** * 保存结果表 */ public handleSaveLoadTable(fieldList: any[]) { const appendFields = (fieldList || []).map( field => new CDataModelManage.MstTbField({ fieldName: field.field_name, fieldAlias: field.field_alias, fieldType: field.field_type, fieldCategory: 'dimension', description: field.description, uid: generateId('__rt_field_'), isFromRt: true, }) ); /** 过滤重复字段,排列到相邻位置 */ appendFields.forEach(field => { const index = this.masterTableInfo.fields.findIndex(f => f.fieldName === field.fieldName); if (index >= 0) { this.masterTableInfo.fields.splice(index + 1, 0, field); field.isAppend = true; } }); /** 过滤系统字段Time,将所有Time字段放到最后 */ const timeFieldList = this.masterTableInfo.fields.filter(f => f.fieldName === __time__.name); let timeFieldListLength = timeFieldList.length; while (timeFieldListLength >= 0) { timeFieldListLength--; const timeFieldIndex = this.masterTableInfo.fields.findIndex(f => f.fieldName === __time__.name); timeFieldIndex > -1 && this.masterTableInfo.fields.splice(timeFieldIndex, 1); } this.masterTableInfo.fields.push(...appendFields.filter(f => !f.isAppend)); if (timeFieldList.length > 0) { /** 追加的Time字段会在默认的系统Time字段之后,此处需要翻转,保证系统默认的Time字段在最后位置 */ this.masterTableInfo.fields.push(...timeFieldList.reverse()); } this.validateFormItems(); this.isLoadRtTableSliderShow = false; this.sendUserActionData({ name: '确定【加载结果表的结构】' }); } /** * 编辑关联维度字段 * @param field * @param index */ public async handleEditDimensionField(field: IDataModelManage.IMasterTableField, index: number) { if (this.canAssociationDimension || !(await this.validateMainFormItems())) { const message = this.canAssociationDimension ? '空表不能进行关联操作' : '请先处理表内错误'; this.$bkMessage({ theme: 'warning', message: this.$t(message), }); return; } this.relatedField = field; this.isReferDimensionTableEdit = true; this.isReferDimensionTableShow = true; } /** * 点击字段加工逻辑弹出侧栏 */ public async handleFieldProcessingLogic(row: IDataModelManage.IMasterTableField, isExtendedField = false) { if (this.canAssociationDimension || !(await this.validateMainFormItems())) { const message = this.canAssociationDimension ? '空表不能进行字段加工操作' : '请先处理表内错误'; this.$bkMessage({ theme: 'warning', message: this.$t(message), }); return; } this.fieldProcessingLogicSlider.editable = !isExtendedField; this.fieldProcessingLogicSlider.field = row; this.fieldProcessingLogicSlider.title = `${row.fieldName} (${row.fieldAlias})`; this.fieldProcessingLogicSlider.isShow = true; } /** * 字段加工逻辑, 保存设置 * @param info */ public handleSaveFieldProcessingLogic(info: object) { const { field, fieldCleanContent, originFieldsDict = [] } = info; const curField = this.masterTableInfo.fields.find(item => item.uid === field.uid); if (curField) { Object.assign(curField, { fieldCleanContent }); } this.handleUpdateFieldLimit(originFieldsDict, field); this.fieldProcessingLogicSlider.isShow = false; this.sendUserActionData({ name: '确定【字段加工逻辑】' }); this.handleFormDataChanged(); } /** * 更新字段编辑/删除限制 * @param originFieldsDict */ public handleUpdateFieldLimit(originFieldsDict: string[] = [], field: IDataModelManage.IMasterTableField) { const originFieldsDictMap = {}; for (const name of originFieldsDict) { originFieldsDictMap[name] = name; } for (const fieldItem of this.masterTableInfo.fields) { if (fieldItem.fieldName === field.fieldName) continue; const editableDeletableInfo = fieldItem.editableDeletableInfo || {}; const limitFields = editableDeletableInfo.fields || []; const limitFieldMap = {}; for (const item of limitFields) { limitFieldMap[item.fieldName] = item.fieldName; } if (originFieldsDictMap[fieldItem.fieldName] && limitFieldMap[field.fieldName]) continue; if (originFieldsDictMap[fieldItem.fieldName] && !limitFieldMap[field.fieldName]) { limitFields.push({ fieldName: field.fieldName }); fieldItem.editableDeletableInfo = Object.assign({}, editableDeletableInfo, { fields: [...limitFields], isUsedByOtherFields: !!limitFields.length, }); } else if (limitFieldMap[field.fieldName]) { const newLimitFields = [...limitFields.filter(item => item.fieldName !== field.fieldName)]; fieldItem.editableDeletableInfo = Object.assign({}, editableDeletableInfo, { fields: newLimitFields, isUsedByOtherFields: !!newLimitFields.length, }); } const { deletable, editable } = this.getFieldLimit(fieldItem.editableDeletableInfo); fieldItem.deletable = deletable; fieldItem.editable = editable; } this.handleUpdateExtendedFieldLimit(); } /** * 获取是否可删除/编辑 * @param editableDeletableInfo */ public getFieldLimit(editableDeletableInfo: IDataModelManage.IEditableDeletableInfo) { let deletable = true; let editable = true; if ( editableDeletableInfo.isUsedByOtherFields || editableDeletableInfo.isUsedByCalcAtom || editableDeletableInfo.isAggregationField || editableDeletableInfo.isConditionField || editableDeletableInfo.isExtendedFieldDeletableEditable === false ) { deletable = false; } else { deletable = true; } if (!deletable || editableDeletableInfo.isJoinField) { editable = false; } else { editable = true; } return { deletable, editable }; } /** * 更新字段 editableDeletableInfo 信息 */ public handleUpdateExtendedFieldLimit() { const mainFields = this.masterTableInfo.fields.filter( (field: IDataModelManage.IMasterTableField) => !field.isExtendedField ); const extendFields = this.masterTableInfo.fields.filter( (field: IDataModelManage.IMasterTableField) => field.isExtendedField ); for (const fieldItem of mainFields) { if (fieldItem.isJoinField) { const curExtends = extendFields.filter( (field: IDataModelManage.IMasterTableField) => field.joinFieldUId === fieldItem.uid ); const isExtendedFieldDeletableEditable = !curExtends.some( (field: IDataModelManage.IMasterTableField) => !field.deletable ); fieldItem.editableDeletableInfo.isExtendedFieldDeletableEditable = isExtendedFieldDeletableEditable; const { deletable, editable } = this.getFieldLimit(fieldItem.editableDeletableInfo); fieldItem.deletable = deletable; fieldItem.editable = editable; } } } /** * 关联维度表保存修改 * @param info */ public handleReferDimensionSave(info: any) { const { joinFieldName, expandFields, relation } = info.result; const index = this.masterTableInfo.fields.findIndex(item => item.fieldName === joinFieldName); if (info.isDelete && info.isEdit) { // 删除关联关系 const relatedIndex = this.masterTableInfo.modelRelation.findIndex( item => item.joinFieldUId === relation.joinFieldUId && item.modelId === relation.modelId ); if (relatedIndex >= 0) { const deleteRelated = this.masterTableInfo.modelRelation.splice(relatedIndex, 1)[0]; // 删除关联字段 for (let i = this.masterTableInfo.fields.length - 1; i > 0; i--) { const curField = this.masterTableInfo.fields[i]; if (deleteRelated && curField.joinFieldName === deleteRelated.fieldName) { this.masterTableInfo.fields.splice(i, 1); } } } if (index >= 0) { const field = this.masterTableInfo.fields[index]; field.isJoinField = false; } } else if (info.isEdit) { const findRelation = this.masterTableInfo.modelRelation.find( item => item.joinFieldUId === relation.joinFieldUId && item.modelId === relation.modelId ); if (findRelation) { // 更新relation信息 Object.assign(findRelation, relation, { relatedModelActiveStatus: 'active' }); // 把旧扩展字段删除 for (let i = this.masterTableInfo.fields.length - 1; i > 0; i--) { const curField = this.masterTableInfo.fields[i]; if (curField.joinFieldName === findRelation.fieldName) { this.masterTableInfo.fields.splice(i, 1); } } } } else { if (index >= 0) { const field = this.masterTableInfo.fields[index]; field.isJoinField = true; this.masterTableInfo.modelRelation.push(relation); } } // 修改 field 设置关联 icon const findField = this.masterTableInfo.fields[index]; if (findField && findField.relatedFieldExist === false) { this.masterTableInfo.fields[index].relatedFieldExist = true; } /** 追加扩展字段到最后位置 */ if (expandFields?.length) { this.masterTableInfo.fields.push(...expandFields); } this.isReferDimensionTableShow = false; this.handleFormDataChanged(); this.sendUserActionData({ name: '确定【关联维度表数据模型】' }); } /** 新建模型 */ public handleCreateNewModelTable() { if ( this.DataModelTabManage.insertItem( new TabItem({ id: 0, name: 'New Model', displayName: this.$t('新建模型'), type: this.activeModelTabItem.type, isNew: true, projectId: this.activeModelTabItem.projectId, modelType: this.activeModelTabItem.modelType, icon: this.activeModelTabItem.icon, lastStep: 0, }), true ) ) { // this.appendRouter({ modelId: 0 }, { project_id: this.activeModelTabItem.projectId }) this.changeRouterWithParams('dataModelEdit', { project_id: this.activeModelTabItem.projectId }, { modelId: 0 }); } } public submitForm() { return new Promise((resolve, reject) => { this.validateMainFormItems().then(validate => { if (validate) { // 将扩展字段放在对应字段后面 const fields = this.masterTableInfo.fields.filter(field => !field._disabled); const submitFields: any[] = []; const extendFields = fields.filter(field => field.isExtendedField); const mainFields = fields.filter(field => !field.isExtendedField); for (const field of mainFields) { submitFields.push(field); if (field.isJoinField) { const curExtends = extendFields.filter(item => item.joinFieldUId === field.uid); submitFields.push(...curExtends); } } submitFields.forEach((field, index) => { field.fieldIndex = index; }); updateMasterTableInfo( this.modelId, this.getServeFormData(submitFields), this.getServeFormData(this.masterTableInfo.modelRelation) ).then(res => { if (res.validateResult()) { const activeTabItem = this.DataModelTabManage.getActiveItem()[0]; activeTabItem.lastStep = res.data.step_id; activeTabItem.publishStatus = res.data.publish_status; this.DataModelTabManage.updateTabItem(activeTabItem); this.DataModelTabManage.dispatchEvent('updateModel', [ { model_id: this.modelId, publish_status: res.data.publish_status, step_id: res.data.step_id, }, ]); this.showMessage(this.$t('保存成功'), 'success'); this.syncPreNextBtnManage.isPreNextBtnConfirm = false; resolve(true); } else { reject(res.message); } }); } else { reject(''); } }); }); } public getFieldEditableInfo(info: object = {}, type: string) { const operation = type === 'delete' ? '删除' : '修改'; const tips = []; if (info.isJoinField && type === 'edit') { tips.push('该字段已引用维度表数据模型,无法修改'); } if (info.isExtendedFieldDeletableEditable === false) { tips.push(`存在扩展字段被引用,无法${operation}`); } if (info.isUsedByCalcAtom) { const usedInfo = (info.calculationAtoms || []) .map(item => `${item.calculationAtomName} (${item.calculationAtomAlias})`) .join('、'); tips.push(`该字段被统计口径 ${usedInfo} 引用,无法${operation}`); } if (info.isAggregationField) { const usedInfo = (info.aggregationFieldIndicators || []) .map(item => `${item.indicatorName} (${item.indicatorAlias})`) .join('、'); tips.push(`该字段被指标 ${usedInfo} 作为聚合字段,无法${operation}`); } if (info.isConditionField) { const usedInfo = (info.conditionFieldIndicators || []) .map(item => `${item.indicatorName} (${item.indicatorAlias})`) .join('、'); tips.push(`该字段被指标 ${usedInfo} 作为过滤字段,无法${operation}`); } if (info.isUsedByOtherFields) { const usedInfo = (info.fields || []).map(item => item.fieldName).join('、'); tips.push(`该字段被 ${usedInfo} 的字段加工逻辑引用,无法${operation}`); } return tips.join('<br />'); } public handleResetOffsetWidth() { this.offsetWidth = document.querySelector('.drag-table-body').offsetWidth - 40; } public handleResizeBody() { const self = this; this.observer = new ResizeObserver(entries => { debounce(self.handleResetOffsetWidth, 200)(); }); this.observer.observe(document.querySelector('.drag-table-body')); } public created() { this.initPreNextManage(); this.loadMasterTableInfo(); } public mounted() { this.handleResizeBody(); this.offsetWidth = document.querySelector('.drag-table-body').offsetWidth - 40; } public beforeDestroy() { if (this.observer) { this.observer.disconnect(); this.observer = null; } } }
the_stack
/// <reference types="node" /> declare module 'wiring-pi' { // Setup export function wiringPiSetup(): number; export function wiringPiSetupGpio(): number; export function wiringPiSetupPhys(): number; export function wiringPiSetupSys(): number; export function setup(mode: string): number; // Core functions export function pinModeAlt(pin: number, mode: number): void; export function pinMode(pin: number, mode: number): void; export function pullUpDnControl(pin: number, pud: number): void; export function digitalRead(pin: number): number; export function digitalWrite(pin: number, state: number): void; export function pwmWrite(pin: number, value: number): void; export function analogRead(pin: number): number; export function analogWrite(pin: number, value: number): void; export function pulseIn(pin: number, state: number): number; export function delay(ms: number): void; export function delayMicroseconds(us: number): void; export function millis(): number; export function micros(): number; // Interrupts export function wiringPiISR(pin: number, edgeType: number, callback: (delta: number) => void): void; export function wiringPiISRCancel(pin: number): void; export const INT_EDGE_FALLING: number; export const INT_EDGE_RISING: number; export const INT_EDGE_BOTH: number; export const INT_EDGE_SETUP: number; // Raspberry Pi hardware specific functions export function piBoardRev(): number; export interface PiBoardId { model: number; rev: number; mem: number; maker: number; overvolted: number; } export function piBoardId(): PiBoardId; export function wpiPinToGpio(pin: number): number; export function physPinToGpio(pin: number): number; export function setPadDrive(group: number, value: number): void; export function getAlt(pin: number): number; export function digitalWriteByte(byte: number): void; export function pwmSetMode(mode: number): void; export function pwmSetRange(range: number): void; export function pwmSetClock(divisor: number): void; export function pwmToneWrite(pin: number, frequency: number): void; export function gpioClockSet(pin: number, frequency: number): void; // Constants // WPI_MODEs export const WPI_MODE_PINS: number; export const WPI_MODE_PHYS: number; export const WPI_MODE_GPIO: number; export const WPI_MODE_GPIO_SYS: number; export const WPI_MODE_PIFACE: number; export const WPI_MODE_UNINITIALISED: number; // pinMode export const INPUT: number; export const OUTPUT: number; export const PWM_OUTPUT: number; export const GPIO_CLOCK: number; export const SOFT_PWM_OUTPUT: number; export const SOFT_TONE_OUTPUT: number; // pullUpDnControl export const PUD_OFF: number; export const PUD_DOWN: number; export const PUD_UP: number; // digitalRead/Write export const HIGH: number; export const LOW: number; // pwmSetMode export const PWM_MODE_BAL: number; export const PWM_MODE_MS: number; // PiBoardId.model export const PI_MODEL_UNKNOWN: number; export const PI_MODEL_A: number; export const PI_MODEL_B: number; export const PI_MODEL_BP: number; export const PI_MODEL_CM: number; export const PI_MODEL_AP: number; export const PI_MODEL_2: number; // PiBoardId.rev export const PI_VERSION_UNKNOWN: number; export const PI_VERSION_1: number; export const PI_VERSION_1_1: number; export const PI_VERSION_1_2: number; export const PI_VERSION_2: number; // PiBoardId,marker export const PI_MAKER_UNKNOWN: number; export const PI_MAKER_EGOMAN: number; export const PI_MAKER_SONY: number; export const PI_MAKER_QISDA: number; export const PI_MAKER_MBEST: number; // arrays export const PI_MODEL_NAMES: string[]; export const PI_REVISION_NAMES: string[]; export const PI_MAKER_NAMES: string[]; // pinModeAlt export const FSEL_INPT: number; export const FSEL_OUTP: number; export const FSEL_ALT0: number; export const FSEL_ALT1: number; export const FSEL_ALT2: number; export const FSEL_ALT3: number; export const FSEL_ALT4: number; export const FSEL_ALT5: number; // I2C export function wiringPiI2CSetup(devId: number): number; export function wiringPiI2CSetupInterface(device: string, devId: number): number; export function wiringPiI2CClose(fd: number): void; export function wiringPiI2CRead(fd: number): number; export function wiringPiI2CReadReg8(fd: number, reg: number): number; export function wiringPiI2CReadReg16(fd: number, reg: number): number; export function wiringPiI2CWrite(fd: number, data: number): number; export function wiringPiI2CWriteReg8(fd: number, reg: number, data: number): number; export function wiringPiI2CWriteReg16(fd: number, reg: number, data: number): number; // SPI export function wiringPiSPIGetFd(channel: number): number; export function wiringPiSPIDataRW(channel: number, data: Buffer): number; export function wiringPiSPISetup(channel: number, speed: number): number; export function wiringPiSPISetupMode(channel: number, speed: number, mode: number): number; export function wiringPiSPIClose(fd: number): void; // Serial export function serialOpen(device: string, baudrate: number): number; export function serialClose(fd: number): void; export function serialFlush(fd: number): void; export function serialPutChar(fd: number, character: number): void; export function serialPuts(fd: number, data: string): void; export function serialPrintf(fd: number, data: string): void; export function serialDataAvail(fd: number): number; export function serialGetchar(fd: number): number; // Shift export function shiftIn(dPin: number, cPin: number, order: number): number; export function shiftOut(dPin: number, cPin: number, order: number, value: number): void; export const LSBFIRST: number; export const MSBFIRST: number; // Soft PWM export function softPwmCreate(pin: number, value: number, range: number): number; export function softPwmWrite(pin: number, value: number): void; export function softPwmStop(pin: number): void; // Soft Servo export function softServoWrite(pin: number, value: number): void; export function softServoSetup(p0: number, p1: number, p2: number, p3: number, p4: number, p5: number, p6: number, p7: number): number; // Soft Tone export function softToneCreate(pin: number): number; export function softToneWrite(pin: number, frequency: number): void; export function softToneStop(pin: number): void; // Extentions // dac7678 export function dac7678Setup(pinBase: number, i2cAddress: number, vrefMode: number): number; export const DAC7678_VREF_MODE_STATIC_ON: number; export const DAC7678_VREF_MODE_STATIC_OFF: number; export const DAC7678_VREF_MODE_FLEXIBLE_ON: number; export const DAC7678_VREF_MODE_FLEXIBLE_ALWAYS_ON: number; export const DAC7678_VREF_MODE_FLEXIBLE_ALWAYS_OFF: number; // drcSerial export function drcSerialSetup(pinBase: number, numPins: number, device: string, baudrate: number): number; // max31855 export function max31855Setup(pinBase: number, spiChannel: number): number; // max5322 export function max5322Setup(pinBase: number, spiChannel: number): number; // mcp23008 export function mcp23008Setup(pinBase: number, i2cAddress: number): number; // mpc23016 export function mpc23016Setup(pinBase: number, i2cAddress: number): number; // mpc23017 export function mpc23017Setup(pinBase: number, i2cAddress: number): number; // mcp23s08 export function mcp23s08Setup(pinBase: number, spiChannel: number, devId: number): number; // mcp23s17 export function mcp23s17Setup(pinBase: number, spiChannel: number, devId: number): number; // mcp3002 export function mcp3002Setup(pinBase: number, spiChannel: number): number; // mcp3004/8 export function mcp3004Setup(pinBase: number, spiChannel: number): number; // mcp3422 export function mcp3422Setup(pinBase: number, i2cAddress: number, sampleRate: number, gain: number): number; export const MCP3422_SR_3_75: number; export const MCP3422_SR_15: number; export const MCP3422_SR_60: number; export const MCP3422_SR_240: number; export const MCP3422_GAIN_1: number; export const MCP3422_GAIN_2: number; export const MCP3422_GAIN_4: number; export const MCP3422_GAIN_8: number; // mcp4802 export function mcp4802Setup(pinBase: number, spiChannel: number): number; // pca9685 export function pca9685Setuo(pinBase: number, i2cAddress: number, frequency: number): number; // pcf8574 export function pcf8574Setup(pinBase: number, i2cAddress: number): number; // pcf8591 export function pcf8591Setup(pinBase: number, i2cAddress: number): number; // sn3218 export function sn3218Setup(pinBase: number): number; // sr595 export function sr595Setup(pinBase: number, numPins: number, dataPin: number, clockPin: number, latchPin: number): number; // DevLib // ds1302 export function ds1302setup(clockPin: number, dataPin: number, csPin: number): void; export function ds1302rtcRead(reg: number): number; export function ds1302rtcWrite(reg: number, data: number): void; export function ds1302ramRead(address: number): number; export function ds1302ramWrite(address: number, data: number): void; export function ds1302clockRead(): number[]; export function ds1302clockWrite(clcokData: number[]): void; export function ds1302trickleCharge(diodes: number, resistors: number): void; // GertBoard export function gertboardAnalogSetup(pinBase: number): number; // LCD export function lcdInit(rows: number, cols: number, bits: number, rs: number, strb: number, d0: number, d1: number, d2: number, d3: number, d4: number, d5: number, d6: number, d7: number): number; export function lcdHome(fd: number): void; export function lcdClear(fd: number): void; export function lcdDisplay(fd: number, state: number): void; export function lcdCursor(fd: number, state: number): void; export function lcdCursorBlink(fd: number, state: number): void; export function lcdSendCommand(fd: number, command: number): void; export function lcdPosition(fd: number, x: number, y: number): void; export function lcdCharDef(fd: number, index: number, data: number[]): void; export function lcdPutchar(fd: number, data: number): void; export function lcdPuts(fd: number, data: string): void; export function lcdPrintf(fd: number, data: string): void; export const MAX_LCDS: number; // LCD 128x64 export function lcd128x64setup(): number; export function lcd128x64setOrigin(x: number, y: number): void; export function lcd128x64setOrientation(orientation: number): void; export function lcd128x64orientCoordinates(): number[]; export function lcd128x64getScreenSize(): number[]; export function lcd128x64point(x: number, y: number, color: number): void; export function lcd128x64line(x0: number, y0: number, x1: number, y1: number, color: number): void; export function lcd128x64lineTo(x: number, y: number, color: number): void; export function lcd128x64rectangle(x1: number, y1: number, x2: number, y2: number, color: number, filled: number): void; export function lcd128x64circle(x: number, y: number, r: number, color: number, filled: number): void; export function lcd128x64ellipse(cx: number, cy: number, xRadius: number, yRadius: number, color: number, filled: number): void; export function lcd128x64putchar(x: number, y: number, c: number, bgColor: number, fgColor: number): void; export function lcd128x64puts(x: number, y: number, data: string, bgColor: number, fgColor: number): void; export function lcd128x64update(): void; export function lcd128x64clear(color: number): void; // cd128x64clear export function maxDetectRead(pin: number): number[]; export function readRHT03(pin: number): number[]; // piFace export function piFaceSetup(pinBase: number): number; // piGlow export function piGlowSetup(clear: number): void; export function piGlow1(leg: number, ring: number, intensity: number): void; export function piGlowLeg(leg: number, intensity: number): void; export function piGlowRing(ring: number, intensity: number): void; export const PIGLOW_RED: number; export const PIGLOW_YELLOW: number; export const PIGLOW_ORANGE: number; export const PIGLOW_GREEN: number; export const PIGLOW_BLUE: number; export const PIGLOW_WHITE: number; // pinNes export function setupNesJoystick(dPin: number, cPin: number, lPin: number): number; export function readNesJoystick(joystick: number): number; export const MAX_NES_JOYSTICKS: number; export const NES_RIGHT: number; export const NES_LEFT: number; export const NES_DOWN: number; export const NES_UP: number; export const NES_START: number; export const NES_SELECT: number; export const NES_A: number; export const NES_B: number; // tcs34725 export function tcs34725Setup(i2cAddress: number, integrationTime: number, gain: number): number; export interface tcs34725RGBC { r: number; g: number; b: number; c: number; } export function tcs34725ReadRGBC(id: number): tcs34725RGBC; export interface tcs34725HSV { h: number; s: number; v: number; } export function tcs34725ReadHSV(id: number): tcs34725HSV; export function tcs34725GetCorrelatedColorTemperature(r: number, g: number, b: number): void; export function tcs34725GetIlluminance(r: number, g: number, b: number): void; export function tcs34725SetInterrupt(id: number, aien: number): void; export function tcs34725ClearInterrupt(id: number): void; export function tcs34725SetInterruptLimits(id: number, low: number, high: number): void; export function tcs34725Enable(id: number): void; export function tcs34725Disable(id: number): void; export const TCS34725_ATIME_2_4MS: number; export const TCS34725_ATIME_24MS: number; export const TCS34725_ATIME_50MS: number; export const TCS34725_ATIME_101MS: number; export const TCS34725_ATIME_154MS: number; export const TCS34725_ATIME_700MS: number; export const TCS34725_GAIN_1: number; export const TCS34725_GAIN_4: number; export const TCS34725_GAIN_16: number; export const TCS34725_GAIN_60: number; export const TCS34725_MAX_TCS34725: number; export const VERSION: string; }
the_stack
* @module WebGL */ /* eslint-disable no-restricted-syntax */ /** Ordered list of render passes which produce a rendered frame. * [[RenderCommands]] organizes its [[DrawCommands]] into a list indexed by RenderPass. * @see [[Pass]] for the type from which the RenderPass for a [[Primitive]] is derived. * @internal */ export const enum RenderPass { None = 0xff, Background = 0, OpaqueLayers, // XY planar models render without depth-testing in order based on priority OpaqueLinear, // Linear geometry that is opaque and needs to be written to the pick data buffers OpaquePlanar, // Planar surface geometry that is opaque and needs to be written to the pick data buffers OpaqueGeneral, // All other opaque geometry (including point clouds and reality meshes) which are not written to the pick data buffers Classification, // Stencil volumes for normal processing of reality data classification. TranslucentLayers, // like Layers but drawn without depth write, blending with opaque Translucent, HiddenEdge, Hilite, OverlayLayers, // Like Layers, but drawn atop all other geometry WorldOverlay, // Decorations ViewOverlay, // Decorations SkyBox, BackgroundMap, HiliteClassification, // Secondary hilite pass for stencil volumes to process hilited classifiers for reality data ClassificationByIndex, // Stencil volumes for processing classification one classifier at a time (used for generating pick data Ids and flashing a single classifier). HilitePlanarClassification, PlanarClassification, VolumeClassifiedRealityData, COUNT, } /** Describes the [[RenderPass]]es in which a [[Primitive]] wants to be rendered. * Generally, each Pass corresponds to a single RenderPass. However a couple of passes specify that the primitive should be rendered * twice, in two different render passes. * [[RenderCommands.addPrimitive]] may ignore the requested Pass. For example, edges typically draw in RenderPass.OpaqueLinear, but * may also draw in RenderPass.HiddenEdge; and translucent geometry may sometimes be rendered in an opaque render pass instead. * @see [[CachedGeometry.getPass]]. * @internal */ export type Pass = "skybox" | // SkyBox "opaque" | // OpaqueGeneral "opaque-linear" | // OpaqueLinear "opaque-planar" | // OpaquePlanar "translucent" | // Translucent "view-overlay" | // ViewOverlay "classification" | // Classification "none" | // None // The following apply to textured meshes when the texture image contains a mix of opaque and transparent pixels. // The mesh requests to be rendered in both opaque and transparent passes, with each pass discarding pixels that don't match that pass. // (i.e., discard transparent pixels during opaque pass and vice-versa). "opaque-translucent" | // OpaqueGeneral and Translucent "opaque-planar-translucent"; // OpaquePlanar and Translucent /** [[Pass]]es that map to two [[RenderPass]]es. * @internal */ export type DoublePass = "opaque-translucent" | "opaque-planar-translucent"; /** [[Pass]]es that map to a single [[RenderPass]]. * @internal */ export type SinglePass = Exclude<Pass, DoublePass>; /** Describes the type of geometry rendered by a ShaderProgram. * @internal */ export const enum GeometryType { IndexedTriangles, IndexedPoints, ArrayedPoints, } /** @internal */ export namespace Pass { // eslint-disable-line @typescript-eslint/no-redeclare /** Return the RenderPass corresponding to the specified Pass. */ export function toRenderPass(pass: SinglePass): RenderPass { switch (pass) { case "skybox": return RenderPass.SkyBox; case "opaque": return RenderPass.OpaqueGeneral; case "opaque-linear": return RenderPass.OpaqueLinear; case "opaque-planar": return RenderPass.OpaquePlanar; case "translucent": return RenderPass.Translucent; case "view-overlay": return RenderPass.ViewOverlay; case "classification": return RenderPass.Classification; case "none": return RenderPass.None; } } /** Return true if the specified Pass renders during RenderPass.Translucent. * @note It is possible for both [[rendersTranslucent]] and [[rendersOpaque]] to return true (or false) for a given Pass. */ export function rendersTranslucent(pass: Pass): boolean { switch (pass) { case "translucent": case "opaque-translucent": case "opaque-planar-translucent": return true; default: return false; } } /** Return true if the specified Pass renders during one of the opaque RenderPasses. * @note It is possible for both [[rendersTranslucent]] and [[rendersOpaque]] to return true for a given Pass. */ export function rendersOpaque(pass: Pass): boolean { switch (pass) { case "opaque-translucent": case "opaque-planar-translucent": case "opaque": case "opaque-planar": case "opaque-linear": return true; default: return false; } } /** Return true if the specified Pass renders both during RenderPass.Translucent and one of the opaque RenderPasses. */ export function rendersOpaqueAndTranslucent(pass: Pass): pass is DoublePass { return "opaque-translucent" === pass || "opaque-planar-translucent" === pass; } export function toOpaquePass(pass: DoublePass): RenderPass { return "opaque-translucent" === pass ? RenderPass.OpaqueGeneral : RenderPass.OpaquePlanar; } } /** Reserved texture units for specific sampler variables, to avoid conflicts between shader components which each have their own textures. * WebGL 1 guarantees a minimum of 8 vertex texture units, and iOS provides no more than that. * WebGL 2 guarantees a minimum of 15 vertex texture units. * @internal */ export enum TextureUnit { // For shaders which know exactly which textures will be used Zero = WebGLRenderingContext.TEXTURE0, One = WebGLRenderingContext.TEXTURE1, Two = WebGLRenderingContext.TEXTURE2, Three = WebGLRenderingContext.TEXTURE3, Four = WebGLRenderingContext.TEXTURE4, Five = WebGLRenderingContext.TEXTURE5, Six = WebGLRenderingContext.TEXTURE6, Seven = WebGLRenderingContext.TEXTURE7, // Last one guaranteed available for WebGL 1 ClipVolume = Zero, FeatureSymbology = One, SurfaceTexture = Two, LineCode = Two, PickFeatureId = Three, PickDepthAndOrder = Four, VertexLUT = Five, // Texture unit 6 is overloaded. Therefore classification, hilite classification, and aux channel are all mutually exclusive. AuxChannelLUT = Six, PlanarClassification = Six, PlanarClassificationHilite = Six, // Texture unit 7 is overloaded. Therefore receiving shadows and thematic display are mutually exclusive. ShadowMap = Seven, ThematicSensors = Seven, // Textures used for up to 3 background or overlay map layers. RealityMesh0 = Two, RealityMesh1 = VertexLUT, // Reality meshes do not use VertexLUT. RealityMesh2 = ShadowMap, // Shadow map when picking -- PickDepthAndOrder otherwise.... // If more than 8 texture units are available, 3 additional background or overlay map layers. RealityMesh3 = WebGLRenderingContext.TEXTURE8, RealityMesh4 = WebGLRenderingContext.TEXTURE9, RealityMesh5 = WebGLRenderingContext.TEXTURE10, RealityMeshThematicGradient = WebGLRenderingContext.TEXTURE11, // Lookup table for indexed edges - used only if WebGL 2 is available. EdgeLUT = WebGLRenderingContext.TEXTURE12, } /** * Defines the order in which primitives are rendered within a GLESList. This is chiefly * used to sort primitives which originate from the same element. e.g., the blanking fill * associated with a text field must always render behind the text; the edges of a surface * must render in front of the surface; etc. * An exception to the 'same element' rule is provided for planar surfaces and edges thereof * sketched onto non-planar surfaces. When the depth test is ambiguous the planar geometry * is always on top of the non-planar surface. This addresses z-fighting when shapes are * sketched onto surfaces, e.g. as part of push-pull modeling workflows. * @internal */ export const enum RenderOrder { None = 0, Background = 1, // i.e., background map drawn without depth BlankingRegion = 2, UnlitSurface = 3, // Distinction only made for whether or not to apply ambient occlusion. LitSurface = 4, Linear = 5, Edge = 6, Silhouette = 7, PlanarBit = 8, PlanarUnlitSurface = UnlitSurface | PlanarBit, PlanarLitSurface = LitSurface | PlanarBit, PlanarLinear = Linear | PlanarBit, PlanarEdge = Edge | PlanarBit, PlanarSilhouette = Silhouette | PlanarBit, } /** @internal */ export function isPlanar(order: RenderOrder): boolean { return order >= RenderOrder.PlanarBit; } /** Flags indicating operations to be performed by the post-process composite step. * @internal */ export const enum CompositeFlags { None = 0, Translucent = 1 << 0, Hilite = 1 << 1, AmbientOcclusion = 1 << 2, } /** Location in boolean array of SurfaceFlags above. * @internal */ export const enum SurfaceBitIndex { HasTexture, ApplyLighting, HasNormals, IgnoreMaterial, TransparencyThreshold, BackgroundFill, HasColorAndNormal, OverrideRgb, NoFaceFront, HasMaterialAtlas, Count, } /** Describes attributes of a MeshGeometry object. Used to conditionally execute portion of shader programs. * @internal */ export const enum SurfaceFlags { None = 0, HasTexture = 1 << SurfaceBitIndex.HasTexture, ApplyLighting = 1 << SurfaceBitIndex.ApplyLighting, HasNormals = 1 << SurfaceBitIndex.HasNormals, // NB: In u_surfaceFlags provided to shader, indicates material color/specular/alpha should be ignored. Has no effect on texture. // If a given feature has the 'ignore material' override set, v_surfaceFlags will be modified to turn on IgnoreMaterial and turn off HasTexture. IgnoreMaterial = 1 << SurfaceBitIndex.IgnoreMaterial, // In HiddenLine and SolidFill modes, a transparency threshold is supplied; surfaces that are more transparent than the threshold are not rendered. TransparencyThreshold = 1 << SurfaceBitIndex.TransparencyThreshold, // For HiddenLine mode BackgroundFill = 1 << SurfaceBitIndex.BackgroundFill, // For textured meshes, the color index in the vertex LUT is unused - we place the normal there instead. // For untextured lit meshes, the normal is placed after the feature ID. HasColorAndNormal = 1 << SurfaceBitIndex.HasColorAndNormal, // For textured meshes, use rgb from v_color instead of from texture. OverrideRgb = 1 << SurfaceBitIndex.OverrideRgb, // For geometry with fixed normals (terrain meshes) we must avoid front facing normal reversal or skirts will be incorrectly lit. NoFaceFront = 1 << SurfaceBitIndex.NoFaceFront, HasMaterialAtlas = 1 << SurfaceBitIndex.HasMaterialAtlas, } /** @internal */ /** 16-bit flags indicating what aspects of a feature's symbology are overridden. * @internal */ export const enum OvrFlags { None = 0, Visibility = 1 << 0, Rgb = 1 << 1, Alpha = 1 << 2, IgnoreMaterial = 1 << 3, // ignore material color, specular properties, and texture. Flashed = 1 << 4, NonLocatable = 1 << 5, // do not draw during pick - allows geometry beneath to be picked. LineCode = 1 << 6, Weight = 1 << 7, Hilited = 1 << 8, Emphasized = 1 << 9, // rendered with "emphasis" hilite settings (silhouette etc). ViewIndependentTransparency = 1 << 10, Rgba = Rgb | Alpha, } /** @internal */ export const enum IsTranslucent { No, Yes, Maybe }
the_stack
import { existsSync, readFileSync } from "fs"; import { isAbsolute, resolve } from "path"; import { Stream } from "stream"; import { CallCredentials as grpcCallCredentials, CallOptions, Channel, ChannelCredentials, Client as GRPCClient, ClientOptions as GRPCClientOptions, credentials as grpcCredentials, Metadata, } from "@grpc/grpc-js"; import type { NodePreference, GRPCClientConstructor, EndPoint, Credentials, BaseOptions, } from "../types"; import { convertToCommandError, debug, NotLeaderError, TimeoutError, UnavailableError, } from "../utils"; import { discoverEndpoint } from "./discovery"; import { parseConnectionString } from "./parseConnectionString"; interface ClientOptions { /** * The amount of time (in milliseconds) to wait after which a keepalive ping is sent on the transport. * Use -1 to disable. * @default 10_000 */ keepAliveInterval?: number; /** * The amount of time (in milliseconds) the sender of the keepalive ping waits for an acknowledgement. * If it does not receive an acknowledgment within this time, it will close the connection. * @default 10_000 */ keepAliveTimeout?: number; /** * Whether or not to immediately throw an exception when an append fails. * @default true */ throwOnAppendFailure?: boolean; } interface DiscoveryOptions { /** * How many times to attempt connection before throwing. */ maxDiscoverAttempts?: number; /** * How long to wait before retrying (in milliseconds). */ discoveryInterval?: number; /** * How long to wait for the request to time out (in seconds). */ gossipTimeout?: number; /** * Preferred node type. */ nodePreference?: NodePreference; } export interface DNSClusterOptions extends DiscoveryOptions, ClientOptions { discover: EndPoint; } export interface GossipClusterOptions extends DiscoveryOptions, ClientOptions { endpoints: EndPoint[]; } export interface SingleNodeOptions extends ClientOptions { endpoint: EndPoint | string; } // This type replaces ConnectionTypeOptions, is now internal. type ConnectionSettings = | DNSClusterOptions | GossipClusterOptions | SingleNodeOptions; export interface ChannelCredentialOptions { insecure?: boolean; rootCertificate?: Buffer; privateKey?: Buffer; certChain?: Buffer; verifyOptions?: Parameters<typeof ChannelCredentials.createSsl>[3]; } interface NextChannelSettings { failedEndpoint: EndPoint; nextEndpoint?: EndPoint; } export class Client { #throwOnAppendFailure: boolean; #connectionSettings: ConnectionSettings; #channelCredentials: ChannelCredentials; #insecure: boolean; #keepAliveInterval: number; #keepAliveTimeout: number; #defaultCredentials?: Credentials; #nextChannelSettings?: NextChannelSettings; #channel?: Promise<Channel>; #grpcClients: Map<GRPCClientConstructor<GRPCClient>, Promise<GRPCClient>> = new Map(); // eslint-disable-next-line jsdoc/require-param /** * Returns a connection from a connection string. * @param connectionString The connection string for your database. */ static connectionString( connectionString: TemplateStringsArray | string, ...parts: Array<string | number | boolean> ): Client { const string: string = Array.isArray(connectionString) ? connectionString.reduce<string>( (acc, chunk, i) => `${acc}${chunk}${parts[i] ?? ""}`, "" ) : (connectionString as string); debug.connection(`Using connection string: ${string}`); const options = parseConnectionString(string); const channelCredentials: ChannelCredentialOptions = { insecure: options.tls === false, }; if (options.tlsCAFile) { if (channelCredentials.insecure) { debug.connection( "tslCAFile passed to insecure connection. Will be ignored." ); } else { const resolvedPath = isAbsolute(options.tlsCAFile) ? options.tlsCAFile : resolve(process.cwd(), options.tlsCAFile); debug.connection(`Resolved tslCAFile option as ${resolvedPath}`); if (!existsSync(resolvedPath)) { throw new Error( "Failed to load certificate file. File was not found." ); } channelCredentials.rootCertificate = readFileSync(resolvedPath); } } if (options.dnsDiscover) { const [discover] = options.hosts; if (options.hosts.length > 1) { debug.connection( `More than one address provided for discovery. Using first: ${discover.address}:${discover.port}.` ); } return new Client( { discover, nodePreference: options.nodePreference, discoveryInterval: options.discoveryInterval, gossipTimeout: options.gossipTimeout, maxDiscoverAttempts: options.maxDiscoverAttempts, throwOnAppendFailure: options.throwOnAppendFailure, keepAliveInterval: options.keepAliveInterval, keepAliveTimeout: options.keepAliveTimeout, }, channelCredentials, options.defaultCredentials ); } if (options.hosts.length > 1) { return new Client( { endpoints: options.hosts, nodePreference: options.nodePreference, discoveryInterval: options.discoveryInterval, gossipTimeout: options.gossipTimeout, maxDiscoverAttempts: options.maxDiscoverAttempts, throwOnAppendFailure: options.throwOnAppendFailure, keepAliveInterval: options.keepAliveInterval, keepAliveTimeout: options.keepAliveTimeout, }, channelCredentials, options.defaultCredentials ); } return new Client( { endpoint: options.hosts[0], throwOnAppendFailure: options.throwOnAppendFailure, keepAliveInterval: options.keepAliveInterval, keepAliveTimeout: options.keepAliveTimeout, }, channelCredentials, options.defaultCredentials ); } constructor( connectionSettings: DNSClusterOptions, channelCredentials?: ChannelCredentialOptions, defaultUserCredentials?: Credentials ); constructor( connectionSettings: GossipClusterOptions, channelCredentials?: ChannelCredentialOptions, defaultUserCredentials?: Credentials ); constructor( connectionSettings: SingleNodeOptions, channelCredentials?: ChannelCredentialOptions, defaultUserCredentials?: Credentials ); constructor( { throwOnAppendFailure = true, keepAliveInterval = 10_000, keepAliveTimeout = 10_000, ...connectionSettings }: ConnectionSettings, channelCredentials: ChannelCredentialOptions = { insecure: false }, defaultUserCredentials?: Credentials ) { if (keepAliveInterval < -1) { throw new Error( `Invalid keepAliveInterval "${keepAliveInterval}". Please provide a positive integer, or -1 to disable.` ); } if (keepAliveTimeout < -1) { throw new Error( `Invalid keepAliveTimeout "${keepAliveTimeout}". Please provide a positive integer, or -1 to disable.` ); } if (keepAliveInterval > -1 && keepAliveInterval < 10_000) { console.warn( `Specified KeepAliveInterval of ${keepAliveInterval} is less than recommended 10_000 ms.` ); } this.#throwOnAppendFailure = throwOnAppendFailure; this.#keepAliveInterval = keepAliveInterval; this.#keepAliveTimeout = keepAliveTimeout; this.#connectionSettings = connectionSettings; this.#insecure = !!channelCredentials.insecure; this.#defaultCredentials = defaultUserCredentials; if (this.#insecure) { debug.connection("Using insecure channel"); this.#channelCredentials = grpcCredentials.createInsecure(); } else { debug.connection( "Using secure channel with credentials %O", channelCredentials ); this.#channelCredentials = grpcCredentials.createSsl( channelCredentials.rootCertificate, channelCredentials.privateKey, channelCredentials.certChain, channelCredentials.verifyOptions ); } } // Internal access to grpc client. private getGRPCClient = async <T extends GRPCClient>( Client: GRPCClientConstructor<T>, debugName: string ): Promise<T> => { if (this.#grpcClients.has(Client)) { debug.connection("Using existing grpc client for %s", debugName); } else { debug.connection("Createing client for %s", debugName); this.#grpcClients.set(Client, this.createGRPCClient(Client)); } return this.#grpcClients.get(Client) as Promise<T>; }; // Internal handled execution protected GRPCStreamCreator = <Client extends GRPCClient, T extends Stream>( Client: GRPCClientConstructor<Client>, debugName: string, creator: (client: Client) => T ) => async (): Promise<T> => { const client = await this.getGRPCClient(Client, debugName); return creator(client).on("error", (err) => this.handleError(client, err) ); }; // Internal handled execution protected execute = async <Client extends GRPCClient, T>( Client: GRPCClientConstructor<Client>, debugName: string, action: (client: Client) => Promise<T> ): Promise<T> => { const client = await this.getGRPCClient(Client, debugName); try { return await action(client); } catch (error) { this.handleError(client, error); throw error; } }; private createGRPCClient = async <T extends GRPCClient>( Client: GRPCClientConstructor<T> ): Promise<T> => { const channelOverride: GRPCClientOptions["channelOverride"] = await this.getChannel(); const client = new Client( null as never, null as never, { channelOverride, } as GRPCClientOptions ); return client; }; private getChannel = async (): Promise<Channel> => { if (this.#channel) { debug.connection("Using existing connection"); return this.#channel; } this.#channel = this.createChannel(); return this.#channel; }; private shouldReconnect = ( err: Error ): [shouldReconnect: boolean, to?: EndPoint] => { const error = convertToCommandError(err); if (error instanceof NotLeaderError) { return [true, error.leader]; } return [error instanceof UnavailableError || error instanceof TimeoutError]; }; protected handleError = async ( client: GRPCClient, error: Error ): Promise<void> => { const [shouldReconnect, nextEndpoint] = this.shouldReconnect(error); if (!shouldReconnect) return; debug.connection("Got reconnection error", error.message); const failedChannel = client.getChannel(); const currentChannel = await this.#channel; if (failedChannel !== currentChannel) { debug.connection("Channel already reconnected"); return; } debug.connection( `Reconnection required${nextEndpoint ? ` to: ${nextEndpoint}` : ""}` ); const [_protocol, address, port] = failedChannel.getTarget().split(":"); this.#grpcClients.clear(); this.#channel = undefined; this.#nextChannelSettings = { failedEndpoint: { address, port: Number.parseInt(port), }, nextEndpoint, }; }; private createChannel = async (): Promise<Channel> => { const uri = await this.resolveUri(); debug.connection( `Connecting to http${ this.#channelCredentials._isSecure() ? "" : "s" }://%s`, uri ); this.#nextChannelSettings = undefined; return new Channel(uri, this.#channelCredentials, { "grpc.keepalive_time_ms": this.#keepAliveInterval < 0 ? Number.MAX_VALUE : this.#keepAliveInterval, "grpc.keepalive_timeout_ms": this.#keepAliveTimeout < 0 ? Number.MAX_VALUE : this.#keepAliveTimeout, }); }; private resolveUri = async (): Promise<string> => { if (this.#nextChannelSettings?.nextEndpoint) { const { address, port } = this.#nextChannelSettings.nextEndpoint; return `${address}:${port}`; } if ("endpoint" in this.#connectionSettings) { const { endpoint } = this.#connectionSettings; return typeof endpoint === "string" ? endpoint : `${endpoint.address}:${endpoint.port}`; } try { const { address, port } = await discoverEndpoint( this.#connectionSettings, this.#channelCredentials, this.#nextChannelSettings?.failedEndpoint ); return `${address}:${port}`; } catch (error) { this.#grpcClients.clear(); this.#channel = undefined; throw error; } }; private createCredentialsMetadataGenerator = ({ username, password, }: Credentials): Parameters< typeof grpcCredentials.createFromMetadataGenerator >[0] => (_, cb) => { const metadata = new Metadata(); if (this.#insecure) { debug.connection( "Credentials are unsupported in insecure mode, and will be ignored." ); } else { const auth = Buffer.from(`${username}:${password}`).toString("base64"); metadata.add("authorization", `Basic ${auth}`); } return cb(null, metadata); }; protected callArguments = ( { credentials = this.#defaultCredentials, requiresLeader }: BaseOptions, callOptions?: CallOptions ): [Metadata, CallOptions] => { const metadata = new Metadata(); const options = callOptions ? { ...callOptions } : {}; if (requiresLeader) { metadata.add("requires-leader", "true"); } if (credentials) { options.credentials = grpcCallCredentials.createFromMetadataGenerator( this.createCredentialsMetadataGenerator(credentials) ); } return [metadata, options]; }; protected get throwOnAppendFailure(): boolean { return this.#throwOnAppendFailure; } }
the_stack
import { Canvas } from '@antv/g-canvas'; import { World } from '@antv/g-webgpu'; import { Compiler } from '@antv/g-webgpu-compiler'; import React, { useEffect, useState } from 'react'; import ReactDOM from 'react-dom'; const gCode = ` import { globalInvocationID } from 'g-webgpu'; const MAX_EDGE_PER_VERTEX; const VERTEX_COUNT; @numthreads(1, 1, 1) class Fruchterman { @in @out u_Data: vec4[]; @in u_K: float; @in u_K2: float; @in u_Center: vec2; @in u_Gravity: float; @in u_ClusterGravity: float; @in u_Speed: float; @in u_MaxDisplace: float; @in u_Clustering: float; @in u_AttributeArray: vec4[]; @in u_ClusterCenters: vec4[]; calcRepulsive(i: int, currentNode: vec4): vec2 { let dx = 0, dy = 0; for (let j = 0; j < VERTEX_COUNT; j++) { if (i != j) { const nextNode = this.u_Data[j]; const xDist = currentNode[0] - nextNode[0]; const yDist = currentNode[1] - nextNode[1]; const dist = (xDist * xDist + yDist * yDist) + 0.01; let param = this.u_K2 / dist; if (dist > 0.0) { dx += param * xDist ; dy += param * yDist ; } } } return [dx, dy]; } calcGravity(currentNode: vec4, nodeAttributes: vec4): vec2 { // let dx = 0, dy = 0; const vx = currentNode[0] - this.u_Center[0]; const vy = currentNode[1] - this.u_Center[1]; const gf = 0.01 * this.u_K * this.u_Gravity; dx = gf * vx; dy = gf * vy; if (this.u_Clustering == 1) { const clusterIdx = int(nodeAttributes[0]); const center = this.u_ClusterCenters[clusterIdx]; const cvx = currentNode[0] - center[0]; const cvy = currentNode[1] - center[1]; const dist = sqrt(cvx * cvx + cvy * cvy) + 0.001; const parma = this.u_K * this.u_ClusterGravity / dist; dx += parma * cvx; dy += parma * cvy; } return [dx, dy]; } calcAttractive(i: int, currentNode: vec4): vec2 { let dx = 0, dy = 0; const arr_offset = int(floor(currentNode[2] + 0.5)); const length = int(floor(currentNode[3] + 0.5)); const node_buffer: vec4; for (let p = 0; p < MAX_EDGE_PER_VERTEX; p++) { if (p >= length) break; const arr_idx = arr_offset + p; // when arr_idx % 4 == 0 update currentNodedx_buffer const buf_offset = arr_idx - arr_idx / 4 * 4; if (p == 0 || buf_offset == 0) { node_buffer = this.u_Data[int(arr_idx / 4)]; } const float_j = buf_offset == 0 ? node_buffer[0] : buf_offset == 1 ? node_buffer[1] : buf_offset == 2 ? node_buffer[2] : node_buffer[3]; const nextNode = this.u_Data[int(float_j)]; const xDist = currentNode[0] - nextNode[0]; const yDist = currentNode[1] - nextNode[1]; const dist = sqrt(xDist * xDist + yDist * yDist) + 0.01; let attractiveF = dist / this.u_K; if (dist > 0.0) { dx -= xDist * attractiveF; dy -= yDist * attractiveF; } } return [dx, dy]; } @main compute() { const i = globalInvocationID.x; const currentNode = this.u_Data[i]; let dx = 0, dy = 0; if (i >= VERTEX_COUNT) { this.u_Data[i] = currentNode; return; } // repulsive const repulsive = this.calcRepulsive(i, currentNode); dx += repulsive[0]; dy += repulsive[1]; // attractive const attractive = this.calcAttractive(i, currentNode); dx += attractive[0]; dy += attractive[1]; // gravity const nodeAttributes = this.u_AttributeArray[i]; const gravity = this.calcGravity(currentNode, nodeAttributes); dx -= gravity[0]; dy -= gravity[1]; // speed dx *= this.u_Speed; dy *= this.u_Speed; // move const distLength = sqrt(dx * dx + dy * dy); if (distLength > 0.0) { const limitedDist = min(this.u_MaxDisplace * this.u_Speed, distLength); this.u_Data[i] = [ currentNode[0] + dx / distLength * limitedDist, currentNode[1] + dy / distLength * limitedDist, currentNode[2], currentNode[3] ]; } } } `; const gCode2 = ` import { globalInvocationID } from 'g-webgpu'; const VERTEX_COUNT; const CLUSTER_COUNT; @numthreads(1, 1, 1) class CalcCenter { @in u_Data: vec4[]; @in u_NodeAttributes: vec4[]; // [[clusterIdx, 0, 0, 0], ...] @in @out u_ClusterCenters: vec4[]; // [[cx, cy, nodeCount, clusterIdx], ...] @main compute() { const i = globalInvocationID.x; const center = this.u_ClusterCenters[i]; let sumx = 0; let sumy = 0; let count = 0; for (let j = 0; j < VERTEX_COUNT; j++) { const attributes = this.u_NodeAttributes[j]; const clusterIdx = int(attributes[0]); const vertex = this.u_Data[j]; if (clusterIdx == i) { sumx += vertex.x; sumy += vertex.y; count += 1; } } this.u_ClusterCenters[i] = [ sumx / count, sumy / count, count, i ]; } } `; const MAX_ITERATION = 1000; const CANVAS_HEIGHT = 600; const CANVAS_WIDTH = 600; const App = React.memo(function Fruchterman() { const [timeElapsed, setTimeElapsed] = useState(0); useEffect(() => { (async () => { // @see https://g6.antv.vision/en/examples/net/forceDirected/#basicForceDirected const data = { nodes: [ { id: '0', label: '0', cluster: 'a', }, { id: '1', label: '1', cluster: 'a', }, { id: '2', label: '2', cluster: 'a', }, { id: '3', label: '3', cluster: 'a', }, { id: '4', label: '4', cluster: 'a', }, { id: '5', label: '5', cluster: 'a', }, { id: '6', label: '6', cluster: 'a', }, { id: '7', label: '7', cluster: 'a', }, { id: '8', label: '8', cluster: 'a', }, { id: '9', label: '9', cluster: 'a', }, { id: '10', label: '10', cluster: 'a', }, { id: '11', label: '11', cluster: 'a', }, { id: '12', label: '12', cluster: 'a', }, { id: '13', label: '13', cluster: 'b', }, { id: '14', label: '14', cluster: 'b', }, { id: '15', label: '15', cluster: 'b', }, { id: '16', label: '16', cluster: 'b', }, { id: '17', label: '17', cluster: 'b', }, { id: '18', label: '18', cluster: 'c', }, { id: '19', label: '19', cluster: 'c', }, { id: '20', label: '20', cluster: 'c', }, { id: '21', label: '21', cluster: 'c', }, { id: '22', label: '22', cluster: 'c', }, { id: '23', label: '23', cluster: 'c', }, { id: '24', label: '24', cluster: 'c', }, { id: '25', label: '25', cluster: 'c', }, { id: '26', label: '26', cluster: 'c', }, { id: '27', label: '27', cluster: 'c', }, { id: '28', label: '28', cluster: 'c', }, { id: '29', label: '29', cluster: 'c', }, { id: '30', label: '30', cluster: 'c', }, { id: '31', label: '31', cluster: 'd', }, { id: '32', label: '32', cluster: 'd', }, { id: '33', label: '33', cluster: 'd', }, ], edges: [ { source: '0', target: '1', }, { source: '0', target: '2', }, { source: '0', target: '3', }, { source: '0', target: '4', }, { source: '0', target: '5', }, { source: '0', target: '7', }, { source: '0', target: '8', }, { source: '0', target: '9', }, { source: '0', target: '10', }, { source: '0', target: '11', }, { source: '0', target: '13', }, { source: '0', target: '14', }, { source: '0', target: '15', }, { source: '0', target: '16', }, { source: '2', target: '3', }, { source: '4', target: '5', }, { source: '4', target: '6', }, { source: '5', target: '6', }, { source: '7', target: '13', }, { source: '8', target: '14', }, { source: '9', target: '10', }, { source: '10', target: '22', }, { source: '10', target: '14', }, { source: '10', target: '12', }, { source: '10', target: '24', }, { source: '10', target: '21', }, { source: '10', target: '20', }, { source: '11', target: '24', }, { source: '11', target: '22', }, { source: '11', target: '14', }, { source: '12', target: '13', }, { source: '16', target: '17', }, { source: '16', target: '18', }, { source: '16', target: '21', }, { source: '16', target: '22', }, { source: '17', target: '18', }, { source: '17', target: '20', }, { source: '18', target: '19', }, { source: '19', target: '20', }, { source: '19', target: '33', }, { source: '19', target: '22', }, { source: '19', target: '23', }, { source: '20', target: '21', }, { source: '21', target: '22', }, { source: '22', target: '24', }, { source: '22', target: '25', }, { source: '22', target: '26', }, { source: '22', target: '23', }, { source: '22', target: '28', }, { source: '22', target: '30', }, { source: '22', target: '31', }, { source: '22', target: '32', }, { source: '22', target: '33', }, { source: '23', target: '28', }, { source: '23', target: '27', }, { source: '23', target: '29', }, { source: '23', target: '30', }, { source: '23', target: '31', }, { source: '23', target: '33', }, { source: '32', target: '33', }, ], }; const center = [CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2]; const nodes = data.nodes.map((n) => ({ x: Math.random() * CANVAS_WIDTH, y: Math.random() * CANVAS_HEIGHT, id: n.id, })); const edges = data.edges; const numParticles = nodes.length; const nodesEdgesArray = buildTextureData(nodes, edges); const { array: attributeArray, count: clusterCount, } = attributesToTextureData('cluster', data.nodes); // compile our kernel code const compiler = new Compiler(); const precompiledBundle = compiler.compileBundle(gCode); const precompiledBundle2 = compiler.compileBundle(gCode2); // create world const world = World.create({ engineOptions: { supportCompute: true, }, }); const timeStart = window.performance.now(); const area = CANVAS_HEIGHT * CANVAS_WIDTH; let maxDisplace = Math.sqrt(area) / 10; const k2 = area / (nodes.length + 1); const k = Math.sqrt(k2); const clusterCenters = []; for (let i = 0; i < clusterCount; i++) { clusterCenters.push(0, 0, 0, 0); } const kernel = world .createKernel(precompiledBundle) .setDispatch([numParticles, 1, 1]) .setBinding({ u_Data: nodesEdgesArray, u_K: k, u_K2: k2, u_Gravity: 10, u_ClusterGravity: 10, u_Speed: 0.1, u_MaxDisplace: maxDisplace, u_Clustering: 1, u_Center: center, u_AttributeArray: attributeArray, u_ClusterCenters: clusterCenters, MAX_EDGE_PER_VERTEX: maxEdgePerVetex, VERTEX_COUNT: numParticles, }); const kernel2 = world .createKernel(precompiledBundle2) .setDispatch([clusterCount, 1, 1]) .setBinding({ u_Data: nodesEdgesArray, u_NodeAttributes: attributeArray, u_ClusterCenters: clusterCenters, VERTEX_COUNT: numParticles, CLUSTER_COUNT: clusterCount, }); for (let i = 0; i < MAX_ITERATION; i++) { await kernel.execute(); kernel2.setBinding({ u_Data: kernel, }); await kernel2.execute(); kernel.setBinding({ u_MaxDisplace: maxDisplace *= 0.99, u_ClusterCenters: kernel2, }); } const finalParticleData = await kernel.getOutput(); setTimeElapsed(window.performance.now() - timeStart); // draw with G renderCircles(finalParticleData, numParticles); window.gwebgpuClean = () => { world.destroy(); }; })(); }, []); return ( <> <div>Elapsed time: {timeElapsed / 1000}s</div> <div>4 clusters</div> <div id="container" /> </> ); }); ReactDOM.render(<App />, document.getElementById('wrapper')); function renderCircles(finalParticleData, numParticles) { const canvas = new Canvas({ container: 'container', center: [], width: CANVAS_WIDTH, height: CANVAS_HEIGHT, }); // draw edges for (let i = 0; i < lineIndexBufferData.length; i += 2) { const x1 = finalParticleData[lineIndexBufferData[i] * 4]; const y1 = finalParticleData[lineIndexBufferData[i] * 4 + 1]; const x2 = finalParticleData[lineIndexBufferData[i + 1] * 4]; const y2 = finalParticleData[lineIndexBufferData[i + 1] * 4 + 1]; const group = canvas.addGroup(); group.addShape('line', { attrs: { x1, y1, x2, y2, stroke: '#1890FF', lineWidth: 1, }, }); } // draw nodes for (let i = 0; i < numParticles * 4; i += 4) { const x = finalParticleData[i]; const y = finalParticleData[i + 1]; const group = canvas.addGroup(); group.addShape('circle', { attrs: { x, y, r: 5, fill: 'red', stroke: 'blue', lineWidth: 2, }, }); } } const lineIndexBufferData = []; let maxEdgePerVetex; // @see https://github.com/nblintao/ParaGraphL/blob/master/sigma.layout.paragraphl.js#L192-L229 function buildTextureData(nodes, edges) { const dataArray = []; const nodeDict = []; const mapIdPos = {}; let i = 0; for (i = 0; i < nodes.length; i++) { const n = nodes[i]; mapIdPos[n.id] = i; dataArray.push(n.x); dataArray.push(n.y); dataArray.push(0); dataArray.push(0); nodeDict.push([]); } for (i = 0; i < edges.length; i++) { const e = edges[i]; nodeDict[mapIdPos[e.source]].push(mapIdPos[e.target]); nodeDict[mapIdPos[e.target]].push(mapIdPos[e.source]); lineIndexBufferData.push(mapIdPos[e.source], mapIdPos[e.target]); } maxEdgePerVetex = 0; for (i = 0; i < nodes.length; i++) { const offset = dataArray.length; const dests = nodeDict[i]; const len = dests.length; dataArray[i * 4 + 2] = offset; dataArray[i * 4 + 3] = dests.length; maxEdgePerVetex = Math.max(maxEdgePerVetex, dests.length); for (let j = 0; j < len; ++j) { const dest = dests[j]; dataArray.push(+dest); } } while (dataArray.length % 4 !== 0) { dataArray.push(0); } return new Float32Array(dataArray); } function attributesToTextureData(clusterKey: string, nodes) { const dataArray = []; const clusterNames = []; nodes.forEach((node) => { const clusterName = node[clusterKey]; let index = clusterNames.indexOf(clusterName); if (index === -1) { clusterNames.push(clusterName); index = clusterNames.length - 1; } dataArray.push(index, 0, 0, 0); }); return { array: new Float32Array(dataArray), count: clusterNames.length, }; }
the_stack
import React, { useState, useReducer, useMemo } from 'react'; import { Button, Upload } from 'antd'; import { ArrowDownOutlined, PlusOutlined } from '@ant-design/icons'; import FormRender, { useForm } from 'form-render'; import JSZip from 'jszip'; import { useSize } from 'ahooks'; import { saveAs } from 'file-saver'; import confetti from 'canvas-confetti'; import { Scaler, useScaler } from '@/components/Scaler'; import Watermark from '@/components/Watermark'; import Control from '@/components/Control'; import HotKey from '@/components/HotKey'; import Market from '@/sections/Market'; import { getBase64 } from '@/untils'; import ImgCrop from 'antd-img-crop'; import 'antd/es/modal/style'; import 'antd/es/slider/style'; import initialImage from '@/assets/watermark.jpg'; import '../../node_modules/pattern.css/dist/pattern.css'; import './index.css'; const schema = { type: 'object', properties: { text: { title: 'Text', readOnly: false, required: false, default: '仅用于办理住房公积金,他用无效。', props: { allowClear: false, }, type: 'string', }, fillStyle: { title: 'Color', readOnly: false, required: false, type: 'string', format: 'color', default: '#00000080', }, fontSize: { title: 'Font Size (px)', readOnly: false, required: false, type: 'number', widget: 'slider', default: 26, min: 12, max: 64, }, rotate: { title: 'Rotate (^)', readOnly: false, required: false, type: 'number', widget: 'slider', default: 20, min: 0, max: 45, }, watermarkWidth: { title: 'Width (px)', readOnly: false, required: false, type: 'number', widget: 'slider', default: 252, min: 100, max: 560, }, watermarkHeight: { title: 'Height (px)', readOnly: false, required: false, type: 'number', widget: 'slider', default: 180, min: 100, max: 360, }, }, displayType: 'column', }; const initalOptions = (() => { const object = schema.properties; let defaultObj = {} as any; for (const key in object) { defaultObj[key] = object[key].default; } return defaultObj; })(); const initialState = { options: initalOptions, fileList: [ { uid: '0', name: '水印示例.png', status: 'done', url: initialImage, preview: initialImage, originFileObj: '', }, ], current: 0, previewImage: initialImage, fileName: '水印示例.png', }; function reducer(state, action) { switch (action.type) { case 'SET_OPTIONS': return { ...state, options: action.payload, }; break; case 'SET_CURRENT': return { ...state, current: action.payload, }; break; default: throw new Error(); } } export default function IndexPage() { const [{ options }, dispatch] = useReducer(reducer, initialState); const form = useForm(); const [scale, scaleAction] = useScaler(60); const { height: screenHeight = window.innerHeight } = useSize(document.body); const [fileList, setFileList] = useState([ { uid: '0', name: '水印示例.png', status: 'done', url: initialImage, preview: initialImage, originFileObj: initialImage, thumbUrl: initialImage, }, ]); const [selected, setSeleted] = useState('0'); const { fileName, previewImage } = useMemo(() => { const selectedFile = fileList.find((value) => value.uid === selected); return { fileName: selectedFile ? selectedFile.name : '未命名', previewImage: selectedFile ? selectedFile.preview : 'https://jdc.jd.com/img/1200x800', }; }, [fileList, selected]); const onPreview = (file: any) => setSeleted(file.uid); const onChange = async ({ file, fileList: currentFileList }) => { const isRemove = currentFileList < fileList; if (isRemove) { if (currentFileList.length === 0) { setSeleted('-1'); setFileList([]); return false; } const lastFile = currentFileList[currentFileList.length - 1]; setSeleted(lastFile.uid); setFileList(currentFileList); } else { file.preview = await getBase64(file.originFileObj); setSeleted(file.uid); setFileList( currentFileList.map((v: any) => { return v.uid === file.uid ? file : v; }), ); } }; const onExport = async () => { const canvasDOM = document.querySelector('canvas'); if (canvasDOM) { canvasDOM.toBlob((blob) => saveAs(blob, fileName)); await onConfetti(); } }; const onConfetti = async () => { const randomInRange = (min: number, max: number) => { return Math.random() * (max - min) + min; }; const sleep = () => new Promise((resolve, reject) => { window.setTimeout(() => resolve(''), 100); }); for (let index = 0; index < 5; index++) { await sleep(); confetti({ angle: randomInRange(55, 125), spread: randomInRange(30, 90), particleCount: randomInRange(50, 100), origin: { y: 0.6 }, }); } }; const onExportAll = async () => { const zip = new JSZip(); zip.file( 'LICENSE', `MIT License Copyright (c) 2021-present Turkyden Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`, ); const renderCanvas = (ms: number = 1000) => { return new Promise<Blob>((resolve, reject) => { window.setTimeout(() => { const canvasDOM = document.querySelector('canvas'); if (canvasDOM) { canvasDOM.toBlob((blob) => resolve(blob)); } else { reject('error: render'); } }, ms); }); }; for (let index = 0; index < fileList.length; index++) { const file = fileList[index]; const { name, uid } = file; setSeleted(uid); const imgBlob = await renderCanvas(); zip.file(name, imgBlob); } const blob = await zip.generateAsync({ type: 'blob' }); saveAs(blob, `watermark_${new Date().getTime()}.zip`); await onConfetti(); }; return ( <div className="w-full"> {/* Header */} <header className="fixed z-40 top-4 left-4 flex justify-start items-center content-center"> <div className="pr-4 text-gray-800"> <div className="text-2xl font-semibold font-sans z-50"> WaterMark Pro </div> </div> <a href="https://github.com/Turkyden/watermark-pro" target="_blank"> <img className="w-24" alt="GitHub Repo stars" src="https://img.shields.io/github/stars/Turkyden/watermark-pro?style=social" /> </a> </header> {/* Canvas */} <section className="pattern-checks-sm | w-full relative bg-gray-200 text-gray-300 flex flex-col justify-center items-center overflow-hidden" style={{ height: screenHeight - 128 }} onWheel={scaleAction.onWheel} > <div style={{ transform: `scale(${scale / 100})` }}> <div className="text-gray-800 text-xl"> <span className="inline-block p-2">{fileName}</span> </div> <Watermark url={previewImage} options={options} /> </div> <Control title="💦 WaterMark Pro" defaultPosition={{ x: -16, y: 16 }}> <FormRender form={form} schema={schema} watch={{ '#': (v) => dispatch({ type: 'SET_OPTIONS', payload: { ...initalOptions, ...v, }, }), }} /> <Button block type="primary" className="bg-gradient-to-r from-indigo-600 via-indigo-500 to-indigo-400" onClick={onExport} > Export </Button> <div className="py-1"></div> <Button block type="ghost" onClick={onExportAll}> Export .zip </Button> </Control> <Scaler scale={scale} {...scaleAction} /> <HotKey /> </section> {/* Upload Block */} <section className="w-full h-34 p-4 overflow-auto bg-gradient-to-r from-indigo-600 via-indigo-500 to-indigo-400 shadow"> {/* <ImgCrop modalTitle="Image Crop" rotate grid> */} <Upload method="get" listType="picture-card" fileList={fileList} onPreview={onPreview} onChange={onChange} > {fileList.length >= 8 ? null : ( <div> <PlusOutlined /> <div style={{ marginTop: 8 }}>Upload</div> </div> )} </Upload> {/* </ImgCrop> */} <div className="animate-bounce w-full absolute bottom-2 left-0 text-center text-gray-300"> <ArrowDownOutlined className="text-2xl" onClick={() => window.scrollTo({ top: window.outerHeight, behavior: 'smooth', }) } /> </div> </section> {/* Market Pages */} <Market /> </div> ); }
the_stack
import { Box, Checkbox, Chip, createStyles, FormControlLabel, Grid, IconButton, Menu, MenuItem, TextField, Theme, withStyles, } from "@material-ui/core"; import { WithStyles } from "@material-ui/core/styles"; import Typography from "@material-ui/core/Typography"; import MoreVertIcon from "@material-ui/icons/MoreVert"; import { Autocomplete, AutocompleteProps, UseAutocompleteProps } from "@material-ui/lab"; import { k8sWsPrefix } from "api/api"; import { push, replace } from "connected-react-router"; import debug from "debug"; import { withNamespace, WithNamespaceProps } from "hoc/withNamespace"; import { withUserAuth, WithUserAuthProps } from "hoc/withUserAuth"; import { produce } from "immer"; import { ApplicationSidebar } from "pages/Application/ApplicationSidebar"; import queryString from "qs"; import React from "react"; import ReconnectingWebSocket from "reconnecting-websocket"; import { ApplicationComponentDetails, PodStatus } from "types/application"; import { formatDate, formatTimestamp } from "utils/date"; import { KSelect } from "widgets/KSelect"; import { Body2 } from "widgets/Label"; import { Loading } from "widgets/Loading"; import { Namespaces } from "widgets/Namespaces"; import { Terminal } from "xterm"; import "xterm/css/xterm.css"; import { BasePage } from "../BasePage"; import { Xterm, XtermRaw } from "./Xterm"; const logger = debug("ws"); const detailedLogger = debug("ws:details"); // generated by https://www.kammerl.de/ascii/AsciiSignature.php const logDocs = " _ _______ _ _____ _ _ _ \n" + "| | |__ __| | | |_ _| | | | | (_) \n" + "| | ___ __ _ | | ___ ___ | | | | _ __ ___| |_ _ __ _ _ ___| |_ _ ___ _ __ ___ \n" + "| | / _ \\ / _` | | |/ _ \\ / _ \\| | | | | '_ \\/ __| __| '__| | | |/ __| __| |/ _ \\| '_ \\/ __|\n" + "| |___| (_) | (_| | | | (_) | (_) | | _| |_| | | \\__ \\ |_| | | |_| | (__| |_| | (_) | | | \\__ \\\n" + "|______\\___/ \\__, | |_|\\___/ \\___/|_| |_____|_| |_|___/\\__|_| \\__,_|\\___|\\__|_|\\___/|_| |_|___/\n" + " __/ | \n" + " |___/ \n\n\n\n" + `\u001b[1;32m1\u001b[0m. Select the pod you are following in the selection menu above. \u001b[1;32m2\u001b[0m. The select supports multiple selections, you can switch the log stream by clicking on the pod's tab. \u001b[1;32m3\u001b[0m. The url is changing with your choices, you can share this url with other colleagues who has permissions. \u001b[1;32m4\u001b[0m. Only the latest logs of each pod are displayed. If you want query older logs with advanced tool, please try learn about kalm log dependency.`; const shellDocs = " _____ _ _ _ _______ _ _____ _ _ _ \n" + "/ ____ | | | | | |__ __| | | |_ _| | | | | (_) \n" + "| (___ | |__ ___| | | | | ___ ___ | | | | _ __ ___| |_ _ __ _ _ ___| |_ _ ___ _ __ ___ \n" + "\\___ \\| '_ \\ / _ \\ | | | |/ _ \\ / _ \\| | | | | '_ \\/ __| __| '__| | | |/ __| __| |/ _ \\| '_ \\/ __|\n" + "____) | | | | __/ | | | | (_) | (_) | | _| |_| | | \\__ \\ |_| | | |_| | (__| |_| | (_) | | | \\__ \\\n" + "|_____/|_| |_|\\___|_|_| |_|\\___/ \\___/|_| |_____|_| |_|___/\\__|_| \\__,_|\\___|\\__|_|\\___/|_| |_|___/\n" + "\n\n\n\n" + `\u001b[1;32m1\u001b[0m. Select the pod you are following in the selection menu above. \u001b[1;32m2\u001b[0m. The select supports multiple selections, you can switch the shell sessions by clicking on the pod's tab. \u001b[1;32m3\u001b[0m. The url is changing with your choices, you can share this url with other colleagues who has permissions.`; interface TabPanelProps { children?: React.ReactNode; index: any; value: any; } function TabPanel(props: TabPanelProps) { const { children, value, index, ...other } = props; return ( <Typography component="div" role="tabpanel" hidden={value !== index} id={`simple-tabpanel-${index}`} aria-labelledby={`simple-tab-${index}`} {...other} > {children} </Typography> ); } const autocompleteStyles = (_theme: Theme) => createStyles({ root: { width: "100%", "& .MuiFormControl-root": { width: "100%", margin: "0 0 16px", "& input": { height: 24, }, }, }, }); const MyAutocomplete = withStyles(autocompleteStyles)( (props: AutocompleteProps<string> & UseAutocompleteProps<string>) => { return <Autocomplete {...props} />; }, ); interface Props extends WithNamespaceProps, WithUserAuthProps, WithStyles<typeof styles> {} const tailLinesOptions = [100, 200, 500, 1000, 2000]; type LogOptions = { tailLines: number; // local filter timestamps refer Lens https://github.com/lensapp/lens/blob/b7974827d2b767d52b1d57fc01a9782e15dce28c/src/renderer/components/%2Bworkloads-pods/pod-logs-dialog.tsx#L141 timestamps: boolean; follow: boolean; previous: boolean; }; interface State { value: [string, string]; subscribedPods: Array<[string, string]>; moreEl: null | HTMLElement; logOptions: LogOptions; timestampsFrom: { [key: string]: string }; } const styles = (theme: Theme) => createStyles({ root: {}, more: { display: "flex", justifyContent: "flex-end", alignItems: "flex-start", }, }); export const generateQueryForPods = (namespace: string, podNames: [string, string][], active?: [string, string]) => { const search = { pods: podNames.length > 0 ? podNames : undefined, active: active || undefined, namespace, }; return queryString.stringify(search); }; export const getPodLogQuery = (namespace: string, pod: PodStatus): string => { const containerNames = pod.containers.map((container) => container.name); const containerName = containerNames[0] === "istio-proxy" ? containerNames[1] || containerNames[0] : containerNames[0]; return generateQueryForPods(namespace, [[pod.name, containerName]], [pod.name, containerName]); }; export class LogStream extends React.PureComponent<Props, State> { private ws: ReconnectingWebSocket; private wsQueueMessages: any[] = []; private terminals: Map<string, XtermRaw> = new Map(); private initalizedFromQuery: boolean = false; private isLog: boolean; // TODO: refactor this flag constructor(props: Props) { super(props); this.state = { value: ["", ""], subscribedPods: [], logOptions: { tailLines: tailLinesOptions[0], timestamps: true, follow: true, previous: false, }, moreEl: null, timestampsFrom: {}, }; this.isLog = window.location.pathname.includes("logs"); this.ws = this.connectWs(); } private saveTerminal = (name: string, el: XtermRaw | null) => { if (el) { this.terminals.set(name, el); } else { this.terminals.delete(name); } }; componentWillUnmount() { if (this.ws) { this.ws.close(); } } componentDidMount() { this.initFromQuery(); } componentDidUpdate(prevProps: Props, prevState: State) { const { activeNamespaceName } = this.props; if (!window.location.search) { this.props.dispatch(push(`/applications/${activeNamespaceName}/components`)); } if (prevState.subscribedPods.length !== this.state.subscribedPods.length || this.state.value !== prevState.value) { // save selected pods in query const search = { ...queryString.parse(window.location.search.replace("?", "")), pods: this.state.subscribedPods.length > 0 ? this.state.subscribedPods : undefined, active: !!this.state.value[0] ? this.state.value : undefined, }; this.props.dispatch( replace({ search: queryString.stringify(search), }), ); } this.initFromQuery(); } private initFromQuery = () => { const { components } = this.props; let pods: string[] = []; components?.forEach((component) => { component.pods.forEach((pod) => { pods.push(pod.name); }); }); if (pods && !this.initalizedFromQuery) { // load selected pods from query, this is useful when first loaded. const queries = queryString.parse(window.location.search.replace("?", "")) as { pods: any; active: [string, string] | undefined; }; let validPods: [string, string][] = []; let validValue: [string, string] = ["", ""]; if (queries.pods) { if (typeof queries.pods === "string") { queries.pods = queryString.parse(queries.pods); } if (typeof queries.pods === "object") { validPods = queries.pods.filter((x: any) => pods.includes(x[0])); } } if (queries.active) { validValue = pods.includes(queries.active[0]) ? queries.active : ["", ""]; } if (this.state.value !== validValue) { this.setState({ value: validValue, }); } if (this.state.subscribedPods.length !== validPods.length) { this.setState({ subscribedPods: validPods, }); } this.initalizedFromQuery = true; } }; private getTimestamps = (logs: string) => { const timestamps = logs.match(/^\d+\S+/gm); if (timestamps && timestamps.length > 0) { return timestamps[0]; } return ""; }; private removeTimestamps = (logs: string) => { return logs.replace(/^\d+.*?\s/gm, ""); }; private writeData = (xterm: Terminal, data: string) => { this.state.logOptions.timestamps ? xterm.write(data) : xterm.write(this.removeTimestamps(data)); }; connectWs = () => { const ws = new ReconnectingWebSocket(`${k8sWsPrefix}/v1alpha1/${this.isLog ? "logs" : "exec"}`); ws.onopen = (evt) => { logger("WS Connection connected."); ws.send( JSON.stringify({ type: "authStatus", }), ); }; const afterWsAuthSuccess = () => { const { subscribedPods } = this.state; if (subscribedPods.length > 0) { Array.from(subscribedPods).forEach(([podName, containerName]) => this.subscribe(podName, containerName)); } while (this.wsQueueMessages.length > 0) { ws.send(this.wsQueueMessages.shift()); } }; ws.onmessage = (evt) => { detailedLogger("Received Message: " + evt.data); const data = JSON.parse(evt.data); if (data.type === "logStreamUpdate") { const timestampsFrom = this.state.timestampsFrom; const timestamp = this.getTimestamps(data.data); if (!timestampsFrom[data.podName]) { this.setState({ timestampsFrom: produce(timestampsFrom, (draft) => { draft[data.podName] = timestamp; }), }); } } if (data.type === "logStreamUpdate" || data.type === "execStreamUpdate") { const terminal = this.terminals.get(data.podName); if (terminal && terminal.xterm) { this.writeData(terminal.xterm, data.data); } return; } if (data.type === "logStreamDisconnected") { const terminal = this.terminals.get(data.podName); if (terminal && terminal.xterm) { this.writeData(terminal.xterm, data.data); // terminal.xterm.writeln("\n\u001b[1;31mPod log stream disconnected\u001b[0m\n"); // terminal.xterm.clear(); } return; } if (data.type === "execStreamDisconnected") { const terminal = this.terminals.get(data.podName); if (terminal && terminal.xterm) { this.writeData(terminal.xterm, data.data); terminal.xterm.writeln("\n\r\u001b[1;31mTerminal disconnected\u001b[0m\n"); } return; } if ((data.type === "authResult" && data.status === 0) || (data.type === "authStatus" && data.status === 0)) { afterWsAuthSuccess(); return; } if (data.type === "authStatus" && data.status === -1) { ws.send( JSON.stringify({ type: "auth", authToken: this.props.authToken, impersonation: this.props.impersonation, }), ); return; } }; ws.onclose = (evt) => { logger("WS Connection closed."); }; return ws; }; subscribe = (podName: string, containerName: string, newLogOptions?: LogOptions) => { logger("subscribe", podName, containerName); const { activeNamespaceName } = this.props; const logOptions = newLogOptions || this.state.logOptions; const terminal = this.terminals.get(podName); if (terminal && terminal.xterm) { terminal.xterm.clear(); } this.sendOrQueueMessage( JSON.stringify({ type: this.isLog ? "subscribePodLog" : "execStartSession", podName, container: containerName, tailLines: logOptions.tailLines, timestamps: true, follow: logOptions.follow, previous: logOptions.previous, namespace: activeNamespaceName, }), ); }; unsubscribe = (podName: string, containerName: string) => { const { activeNamespaceName } = this.props; logger("unsubscribe", podName, containerName); this.sendOrQueueMessage( JSON.stringify({ type: this.isLog ? "unsubscribePodLog" : "execEndSession", podName, container: containerName, namespace: activeNamespaceName, }), ); }; sendOrQueueMessage = (msg: any) => { if (this.ws.readyState !== 1) { this.wsQueueMessages.push(msg); } else { this.ws.send(msg); } }; getAllPods = (): PodStatus[] => { const { components } = this.props; let pods: PodStatus[] = []; components?.forEach((component: ApplicationComponentDetails) => { component.pods?.forEach((pod: PodStatus) => { pods.push(pod); }); }); return pods; }; onInputChange = (_event: React.ChangeEvent<{}>, x: string[]) => { const { subscribedPods } = this.state; const { value } = this.state; const subscribedPodNames = subscribedPods.map((x) => x[0]); const currentPodNames = x; const pods = this.getAllPods(); let newValue = value; const currentPods: Array<[string, string]> = currentPodNames.map((podName) => { const subscribedPod = subscribedPods.find((x) => x[0] === podName); if (subscribedPod) { return subscribedPod; } else { const pod = pods.find((x) => x.name === podName)!; const containerNames = pod.containers.map((x) => x.name); return [podName, containerNames[0]]; } }); subscribedPods.forEach(([podName, containerName]) => { if (!currentPodNames.includes(podName)) { this.unsubscribe(podName, containerName); if (podName === value[0]) { newValue = ["", ""]; } } }); currentPodNames.forEach((podName) => { const pod = pods.find((x) => x.name === podName)!; const containerNames = pod.containers.map((x) => x.name); if (!subscribedPodNames.includes(podName)) { this.subscribe(podName, containerNames[0]); } if (!newValue[0]) { newValue = [podName, containerNames[0]]; } }); this.setState({ subscribedPods: currentPods, value: newValue }); }; onInputContainerChange = (x: any) => { const { subscribedPods, value } = this.state; let newSubscribedPods: Array<[string, string]> = []; subscribedPods?.forEach(([podName, containerName]) => { if (podName === value[0]) { newSubscribedPods.push([podName, x]); this.unsubscribe(podName, containerName); this.subscribe(podName, x); } else { newSubscribedPods.push([podName, containerName]); } }); this.setState({ subscribedPods: newSubscribedPods, value: [value[0], x] }); }; onLogOptionsChange = (newLogOptions: LogOptions) => { const { subscribedPods } = this.state; subscribedPods?.forEach(([podName, containerName]) => { this.unsubscribe(podName, containerName); this.subscribe(podName, containerName, newLogOptions); }); this.setState({ logOptions: newLogOptions }); }; private renderInputPod() { const { components } = this.props; let podNames: string[] = []; components?.forEach((component: ApplicationComponentDetails) => { component.pods?.forEach((pod: PodStatus) => { podNames.push(pod.name); }); }); const { value, subscribedPods } = this.state; const subscribedPodNames = subscribedPods.map((p) => p[0]); const names = podNames!.filter((x) => !subscribedPodNames.includes(x)); return ( <MyAutocomplete multiple id="tags-filled" options={names} onChange={this.onInputChange} value={Array.from(subscribedPodNames)} renderTags={(options: string[], getTagProps) => options.map((option: string, index: number) => { return ( <Chip variant="outlined" label={option} size="small" onClick={(event) => { const value = subscribedPods.find((x) => x[0] === option)!; this.setState({ value }); event.stopPropagation(); }} color={option === value[0] ? "primary" : "default"} {...getTagProps({ index })} /> ); }) } renderInput={(params) => ( <TextField label={"Pods"} {...params} variant="outlined" size="small" placeholder="Select the pod you want to view logs" /> )} /> ); } private renderInputContainer() { const { value } = this.state; const pods = this.getAllPods(); const pod = pods.find((x) => value[0] === x.name)!; const containerNames = pod ? pod.containers.map((container) => container.name) : []; return ( <KSelect label="Container" value={value[1]} options={containerNames.map((x) => { return { value: x, text: x, }; })} onChange={this.onInputContainerChange} /> ); } private renderInputTailLines() { const { logOptions } = this.state; return ( <KSelect label="Lines" value={logOptions.tailLines} options={tailLinesOptions.map((x) => { return { value: x, text: `${x}`, }; })} onChange={(x) => { this.onLogOptionsChange( produce(logOptions, (draft) => { draft.tailLines = x as number; }), ); }} /> ); } handleClickMore = (event: React.MouseEvent<HTMLButtonElement>) => { this.setState({ moreEl: event.currentTarget }); }; handleCloseMore = (logOptions?: LogOptions) => { if (logOptions) { this.onLogOptionsChange(logOptions); } this.setState({ moreEl: null }); }; private renderFromTo() { const { value, timestampsFrom } = this.state; const podName = value[0]; if (!podName || !timestampsFrom[podName]) { return null; } return ( <Box width="100%" display="flex" justifyContent="flex-end"> <Box pt="3px"> <Box display="flex"> <Box width="50px"> <Body2>From</Body2> </Box> <Body2>{formatTimestamp(timestampsFrom[podName])}</Body2> </Box> <Box display="flex"> <Box width="50px" pl={2}> <Body2>To</Body2> </Box> <Body2>{formatDate(new Date())}</Body2> </Box> </Box> </Box> ); } private renderMore() { const { classes } = this.props; const { moreEl, logOptions } = this.state; const options: { key: "timestamps" | "follow" | "previous"; text: string; }[] = [ { key: "timestamps", text: "Show timestamps", }, { key: "follow", text: "Follow logs", }, { key: "previous", text: "Show previous logs", }, ]; return ( <div className={classes.more}> <IconButton aria-label="more" aria-controls="log-more-menu" aria-haspopup="true" onClick={this.handleClickMore}> <MoreVertIcon /> </IconButton> <Menu id="log-more-menu" anchorEl={moreEl} keepMounted open={Boolean(moreEl)} onClose={() => this.handleCloseMore()} > {options.map((option) => { return ( <MenuItem key={option.key} onClick={(e) => { e.stopPropagation(); e.preventDefault(); this.handleCloseMore( produce(logOptions, (draft) => { draft[option.key] = !logOptions[option.key]; }), ); }} > <FormControlLabel control={<Checkbox checked={logOptions[option.key]} name={option.key} />} label={option.text} /> </MenuItem> ); })} </Menu> </div> ); } private renderLogTerminal = (podName: string, initializedContent?: string) => { const { value } = this.state; return ( <Xterm innerRef={(el) => this.saveTerminal(podName, el)} show={value[0] === podName} initializedContent={initializedContent} terminalOptions={{ cursorBlink: false, cursorStyle: "bar", cursorWidth: 0, disableStdin: true, convertEol: true, // fontSize: 12, theme: { selection: "rgba(255, 255, 72, 0.5)" }, }} /> ); }; private renderExecTerminal = (podName: string, initializedContent?: string) => { const { value } = this.state; return ( <Xterm innerRef={(el) => this.saveTerminal(podName, el)} show={value[0] === podName} initializedContent={initializedContent} termianlOnData={(data: any) => { this.sendOrQueueMessage( JSON.stringify({ type: "stdin", podName: podName, namespace: this.props.activeNamespaceName, data: data, }), ); }} termianlOnBinary={(data: any) => { this.sendOrQueueMessage( JSON.stringify({ type: "stdin", podName: podName, namespace: this.props.activeNamespaceName, data: data, }), ); }} terminalOnResize={(size: { cols: number; rows: number }) => { this.sendOrQueueMessage( JSON.stringify({ type: "resize", podName: podName, namespace: this.props.activeNamespaceName, data: `${size.cols},${size.rows}`, }), ); }} terminalOptions={{ // convertEol: true, // fontSize: 12, theme: { selection: "rgba(255, 255, 72, 0.5)" }, }} /> ); }; public render() { const { isNamespaceLoading, activeNamespace } = this.props; const { value, subscribedPods } = this.state; return ( <BasePage secondHeaderLeft={<Namespaces />} secondHeaderRight={this.isLog ? "Log" : "Shell"} leftDrawer={<ApplicationSidebar />} fullContainer={true} > <Box p={2}> {isNamespaceLoading || !activeNamespace ? ( <Loading /> ) : ( <> {this.isLog ? ( <Grid container spacing={2}> <Grid item md={5}> {this.renderInputPod()} </Grid> <Grid item md={2}> {this.renderInputContainer()} </Grid> <Grid item md={2}> {this.renderInputTailLines()} </Grid> <Grid item md={2}> {this.renderFromTo()} </Grid> <Grid item md={1}> {this.renderMore()} </Grid> </Grid> ) : ( <Grid container spacing={2}> <Grid item md={8}> {this.renderInputPod()} </Grid> <Grid item md={4}> {this.renderInputContainer()} </Grid> </Grid> )} <TabPanel value={value[0]} key={"empty"} index={""}> {this.isLog ? this.renderLogTerminal("", logDocs) : this.renderLogTerminal("", shellDocs)} </TabPanel> {Array.from(subscribedPods).map(([podName]) => { return ( <TabPanel value={value[0]} key={podName} index={podName}> {this.isLog ? this.renderLogTerminal(podName) : this.renderExecTerminal(podName)} </TabPanel> ); })} </> )} </Box> </BasePage> ); } } export const Log = withStyles(styles)(withNamespace(withUserAuth(LogStream)));
the_stack
import { Application, AppRole, AppRoleAssignment, OAuth2PermissionGrant, PermissionScope, RequiredResourceAccess, ResourceAccess, ServicePrincipal } from '@microsoft/microsoft-graph-types'; import { AxiosRequestConfig } from 'axios'; import { Cli, Logger } from '../../../../cli'; import Command from '../../../../Command'; import request from '../../../../request'; import * as appGetCommand from '../../../aad/commands/app/app-get'; import { Options as AppGetCommandOptions } from '../../../aad/commands/app/app-get'; import AppCommand, { AppCommandArgs } from '../../../base/AppCommand'; import commands from '../../commands'; interface ApiPermission { resource: string; permission: string; type: string; } interface ServicePrincipalInfo { appId?: string; id?: string; } enum GetServicePrincipal { withPermissions, withPermissionDefinitions } class AppPermissionListCommand extends AppCommand { public get name(): string { return commands.PERMISSION_LIST; } public get description(): string { return 'Lists API permissions for the current AAD app'; } public commandAction(logger: Logger, args: AppCommandArgs, cb: (err?: any) => void): void { this .getServicePrincipal({ appId: this.appId }, logger, GetServicePrincipal.withPermissions) .then(servicePrincipal => { if (servicePrincipal) { // service principal found, get permissions from the service principal return this.getServicePrincipalPermissions(servicePrincipal, logger); } else { // service principal not found, get permissions from app registration return this.getAppRegPermissions(this.appId as string, logger); } }) .then(permissions => { logger.log(permissions); cb(); }, err => this.handleRejectedODataJsonPromise(err, logger, cb)); } private async getServicePrincipal(servicePrincipalInfo: ServicePrincipalInfo, logger: Logger, mode: GetServicePrincipal): Promise<ServicePrincipal | undefined> { if (this.verbose) { logger.logToStderr(`Retrieving service principal ${servicePrincipalInfo.appId ?? servicePrincipalInfo.id}`); } const lookupUrl: string = servicePrincipalInfo.appId ? `?$filter=appId eq '${servicePrincipalInfo.appId}'&` : `/${servicePrincipalInfo.id}?`; const requestOptions: AxiosRequestConfig = { url: `${this.resource}/v1.0/servicePrincipals${lookupUrl}$select=appId,id,displayName`, headers: { accept: 'application/json;odata.metadata=none' }, responseType: 'json' }; const response = await request.get<{ value: ServicePrincipal[] } | ServicePrincipal>(requestOptions); if ((servicePrincipalInfo.id && !response) || (servicePrincipalInfo.appId && (response as { value: ServicePrincipal[] }).value.length === 0)) { return undefined; } const servicePrincipal = servicePrincipalInfo.appId ? (response as { value: ServicePrincipal[] }).value[0] : response as ServicePrincipal; if (this.verbose) { logger.logToStderr(`Retrieving permissions for service principal ${servicePrincipal.id}...`); } const permissionsPromises = []; switch (mode) { case GetServicePrincipal.withPermissions: const appRoleAssignmentsRequestOptions: AxiosRequestConfig = { url: `${this.resource}/v1.0/servicePrincipals/${servicePrincipal.id}/appRoleAssignments`, headers: { accept: 'application/json;odata.metadata=none' }, responseType: 'json' }; const oauth2PermissionGrantsRequestOptions: AxiosRequestConfig = { url: `${this.resource}/v1.0/servicePrincipals/${servicePrincipal.id}/oauth2PermissionGrants`, headers: { accept: 'application/json;odata.metadata=none' }, responseType: 'json' }; permissionsPromises.push(...[ request.get<{ value: AppRoleAssignment[] }>(appRoleAssignmentsRequestOptions), request.get<{ value: OAuth2PermissionGrant[] }>(oauth2PermissionGrantsRequestOptions) ]); break; case GetServicePrincipal.withPermissionDefinitions: const oauth2PermissionScopesRequestOptions: AxiosRequestConfig = { url: `${this.resource}/v1.0/servicePrincipals/${servicePrincipal.id}/oauth2PermissionScopes`, headers: { accept: 'application/json;odata.metadata=none' }, responseType: 'json' }; const appRolesRequestOptions: AxiosRequestConfig = { url: `${this.resource}/v1.0/servicePrincipals/${servicePrincipal.id}/appRoles`, headers: { accept: 'application/json;odata.metadata=none' }, responseType: 'json' }; permissionsPromises.push(...[ request.get<{ value: PermissionScope[] }>(oauth2PermissionScopesRequestOptions), request.get<{ value: AppRole[] }>(appRolesRequestOptions) ]); break; } const permissions = await Promise.all(permissionsPromises); switch (mode) { case GetServicePrincipal.withPermissions: servicePrincipal.appRoleAssignments = permissions[0].value; servicePrincipal.oauth2PermissionGrants = permissions[1].value as any; break; case GetServicePrincipal.withPermissionDefinitions: servicePrincipal.oauth2PermissionScopes = permissions[0].value as any; servicePrincipal.appRoles = permissions[1].value as any; break; } return servicePrincipal; } private async getServicePrincipalPermissions(servicePrincipal: ServicePrincipal, logger: Logger): Promise<ApiPermission[]> { if (this.verbose) { logger.logToStderr(`Resolving permissions for the service principal...`); } const apiPermissions: ApiPermission[] = []; // hash table for resolving resource IDs to names const resourceLookup: { [key: string]: string } = {}; // list of service principals for which to load permissions const servicePrincipalsToResolve: ServicePrincipalInfo[] = []; const appRoleAssignments = servicePrincipal.appRoleAssignments as AppRoleAssignment[]; apiPermissions.push(...appRoleAssignments.map(appRoleAssignment => { // store resource name for resolving OAuth2 grants resourceLookup[appRoleAssignment.resourceId as string] = appRoleAssignment.resourceDisplayName as string; // add to the list of service principals to load to get the app role // display name if (!servicePrincipalsToResolve.find(r => r.id === appRoleAssignment.resourceId)) { servicePrincipalsToResolve.push({ id: appRoleAssignment.resourceId as string }); } return { resource: appRoleAssignment.resourceDisplayName as string, // we store the app role ID temporarily and will later resolve to display name permission: appRoleAssignment.appRoleId as string, type: 'Application' }; })); const oauth2Grants = servicePrincipal.oauth2PermissionGrants as OAuth2PermissionGrant[]; oauth2Grants.forEach(oauth2Grant => { // see if we can resolve the resource name from the resources // retrieved from app role assignments const resource = resourceLookup[oauth2Grant.resourceId as string] ?? oauth2Grant.resourceId as string; if (resource === oauth2Grant.resourceId as string && !servicePrincipalsToResolve.find(r => r.id === oauth2Grant.resourceId)) { // resource name not found in the resources // add it to the list of resources to resolve servicePrincipalsToResolve.push({ id: oauth2Grant.resourceId as string }); } const scopes = (oauth2Grant.scope as string).split(' '); scopes.forEach(scope => { apiPermissions.push({ resource, permission: scope, type: 'Delegated' }); }); }); if (servicePrincipalsToResolve.length > 0) { const servicePrincipals = await Promise .all(servicePrincipalsToResolve .map(servicePrincipalInfo => this.getServicePrincipal(servicePrincipalInfo, logger, GetServicePrincipal.withPermissionDefinitions) as ServicePrincipal)); servicePrincipals.forEach(servicePrincipal => { apiPermissions.forEach(apiPermission => { if (apiPermission.resource === servicePrincipal.id) { apiPermission.resource = servicePrincipal.displayName as string; } if (apiPermission.resource === servicePrincipal.displayName && apiPermission.type === 'Application') { apiPermission.permission = (servicePrincipal.appRoles as AppRole[]) .find(appRole => appRole.id === apiPermission.permission)?.value as string ?? apiPermission.permission; } }); }); } return apiPermissions; } private async getAppRegistration(appId: string, logger: Logger): Promise<Application> { if (this.verbose) { logger.logToStderr(`Retrieving Azure AD application registration ${appId}`); } const options: AppGetCommandOptions = { appId: appId, output: 'json', debug: this.debug, verbose: this.verbose }; const output = await Cli.executeCommandWithOutput(appGetCommand as Command, { options: { ...options, _: [] } }); if (this.debug) { logger.logToStderr(output.stderr); } return JSON.parse(output.stdout) as Application; } private async getAppRegPermissions(appId: string, logger: Logger): Promise<ApiPermission[]> { const application = await this.getAppRegistration(appId, logger); if ((application.requiredResourceAccess as RequiredResourceAccess[]).length === 0) { return []; } const servicePrincipalsToResolve: ServicePrincipalInfo[] = (application.requiredResourceAccess as RequiredResourceAccess[]) .map(resourceAccess => { return { appId: resourceAccess.resourceAppId as string }; }); const servicePrincipals = await Promise .all(servicePrincipalsToResolve.map(servicePrincipalInfo => this.getServicePrincipal(servicePrincipalInfo, logger, GetServicePrincipal.withPermissionDefinitions) as ServicePrincipal)); const apiPermissions: ApiPermission[] = []; (application.requiredResourceAccess as RequiredResourceAccess[]).forEach(requiredResourceAccess => { const servicePrincipal = servicePrincipals .find(servicePrincipal => servicePrincipal?.appId === requiredResourceAccess.resourceAppId as string); const resourceName = servicePrincipal?.displayName as string ?? requiredResourceAccess.resourceAppId as string; (requiredResourceAccess.resourceAccess as ResourceAccess[]).forEach(permission => { apiPermissions.push({ resource: resourceName, permission: this.getPermissionName(permission.id as string, permission.type as string, servicePrincipal), type: permission.type === 'Role' ? 'Application' : 'Delegated' }); }); }); return apiPermissions; } private getPermissionName(permissionId: string, permissionType: string, servicePrincipal: ServicePrincipal | undefined): string { if (!servicePrincipal) { return permissionId; } switch (permissionType) { case 'Role': return (servicePrincipal.appRoles as AppRole[]) .find(appRole => appRole.id === permissionId)?.value as string ?? permissionId; case 'Scope': return (servicePrincipal.oauth2PermissionScopes as PermissionScope[]) .find(permissionScope => permissionScope.id === permissionId)?.value as string ?? permissionId; } /* c8 ignore next 4 */ // permissionType is either 'Scope' or 'Role' but we need a safe default // to avoid building errors. This code will never be reached. return permissionId; } } module.exports = new AppPermissionListCommand();
the_stack
// geometry constants const TILE_WIDTH = 80 const TILE_HEIGHT = 36 const HEX_GRID_SIZE = 200 // hex grid is 200x200 interface Point { x: number; y: number; } interface Point3 { x: number; y: number; z: number; } interface BoundingBox { x: number; y: number; w: number; h: number; } function toTileNum(position: Point): number { return position.y * 200 + position.x } function fromTileNum(tile: number): Point { return {x: tile % 200, y: Math.floor(tile / 200)} // TODO: use x|0 instead of floor for some of these } function tileToScreen(x: number, y: number): Point { x = 99 - x // this algorithm expects x to be reversed var sx = 4752 + (32 * y) - (48 * x) var sy = (24 * y) + (12 * x) return {x: sx, y: sy} } function tileFromScreen(x: number, y: number): Point { var off_x = -4800 + x var off_y = y var xx = off_x - off_y * 4 / 3 var tx = xx / 64 if (xx >= 0) tx++ tx = -tx var yy = off_y + off_x / 4 var ty = yy / 32 if (yy < 0) ty-- return {x: 99 - Math.round(tx), y: Math.round(ty)} } function hexToTile(pos: Point): Point { // Calculate screen position of `pos`, then look up which roof tile that belongs to, // and then calculate the square tile position from the screen position. const scrPos = hexToScreen(pos.x, pos.y); return tileFromScreen(scrPos.x, scrPos.y); } function centerTile(): Point { return hexFromScreen(cameraX + ((SCREEN_WIDTH / 2)|0) - 32, cameraY + ((SCREEN_HEIGHT / 2)|0) - 16) /*return hexFromScreen(cameraX + Math.floor((SCREEN_WIDTH - 32) / 2), cameraY + Math.floor((SCREEN_HEIGHT - 16) / 2))*/ } var tile_center = {x: 0, y: 0} function setCenterTile() { tile_center = centerTile() } // tile_coord(0x319E) == {x: -336, y: -250} // tile_coord(0x319F) should be the same // tile_coord(0x5018) should be (230, 304) function tile_coord(tileNum: number): Point|null { if(tileNum < 0 || tileNum >= 200*200) return null //var tile_x = 0x62 // todo: ? //var tile_y = 0x64 // todo: ? setCenterTile() var tile_x = /*199 -*/ tile_center.x var tile_y = tile_center.y var tile_offx = 272 var tile_offy = 182 var a2 = tile_offx // x (normally this would be cameraX aka tile_offx) var a3 = tile_offy // y (normally this would be cameraY aka tile_offy) var v3 = 200 - 1 - (tileNum % 200) var v4 = Math.floor(tileNum / 200) var v5 = Math.floor((v3 - tile_x) / -2) a2 += 48 * Math.ceil((v3 - tile_x) / 2) // TODO: ceil, round or floor? a3 += 12 * v5 console.log("v3:", v3, "=", v3&1) if ( v3 & 1 ) { if ( v3 > tile_x ) { a2 += 32 } else { a2 -= 16 a3 += 12 } } var v6 = v4 - tile_y a2 += 16 * v6 a3 += 12 * v6 return {x: a2, y: a3} } /* function tile_coord(tileNum: number): Point { if(tileNum < 0 || tileNum >= 200*200) return null var tile_x = 0x62 // todo: ? this seems to be the same as tile_offx right now var tile_y = 0x64 // same, but for tile_offy var a2 = tile_x // x (normally this would be cameraX aka tile_offx) var a3 = tile_y // y (normally this would be cameraY aka tile_offy) var v3 = 200 - 1 - tileNum % 200 var v4 = Math.floor(tileNum / 200) var v5 = Math.floor((v3 - tile_x) / -2) a2 += 48 * Math.floor((v3 - tile_x) / 2) a3 += 12 * v5 if ( v3 & 1 ) { if ( v3 > tile_x ) { a2 += 32 } else { a2 -= 16 a3 += 12 } } var v6 = v4 - tile_y a2 += 16 * v6 a3 += 12 * v6 return {x: a2, y: a3} }*/ function hexToScreen(x: number, y: number): Point { var sx = 4816 - ((((x + 1) >> 1) << 5) + ((x >> 1) << 4) - (y << 4)) var sy = ((12 * (x >> 1)) + (y * 12)) + 11 return {x: sx, y: sy} } function hexFromScreen(x: number, y: number): Point { var x0 = 4800 var y0 = 0 var nx, ny if (x - x0 < 0) nx = (x - x0 + 1) / 16 - 1 else nx = (x - x0) / 16 if (y - y0 < 0) ny = (y - y0 + 1) / 12 - 1 else ny = (y - y0) / 12 if (Math.abs(nx) % 2 != Math.abs(ny) % 2) nx--; var xhBase = x0 + 16 * nx var yhBase = y0 + 12 * ny var hx = (4 * (yhBase - y0) - 3 * (xhBase - x0)) / 96 var hy = (yhBase - y0) / 12 - hx / 2 var dx = x - xhBase var dy = y - yhBase // XXX: Some of these cases fall through, should be inspected. switch(dy) { case 0: if (dx < 12) { hy--; break; } if (dx > 18) { if (hx % 2 == 1) hy--; hx--; break; } case 1: if (dx < 8) { hx--; break; } if (dx > 23) { if (hx % 2 == 1) hy--; hx--; break; } case 2: if (dx < 4) { hy--; break; } if (dx > 28) { if (hx % 2 == 1) hy--; hx--; break; } default: break; } return {x: Math.round(hx), y: Math.round(hy)} } function hexNeighbors(position: Point): Point[] { const neighbors: Point[] = [] var x = position.x var y = position.y function n(x: number, y: number) { neighbors.push({x: x, y: y}) } if(x % 2 === 0) { n(x-1,y) n(x-1,y+1) n(x,y+1) n(x+1,y+1) n(x+1,y) n(x,y-1) } else { n(x-1,y-1) n(x-1,y) n(x,y+1) n(x+1,y) n(x+1,y-1) n(x,y-1) } return neighbors } function hexInDirection(position: Point, dir: number): Point { return hexNeighbors(position)[dir] } function hexInDirectionDistance(position: Point, dir: number, distance: number): Point { if(distance === 0) { console.log("hexInDirectionDistance: distance=0") return position } var tile = hexInDirection(position, dir) for(var i = 0; i < distance-1; i++) // repeat for each further distance tile = hexInDirection(tile, dir) return tile } function directionOfDelta(xa: number, ya: number, xb: number, yb: number): number|null { var neighbors = hexNeighbors({x: xa, y: ya}) for(var i = 0; i < neighbors.length; i++) { if(neighbors[i].x === xb && neighbors[i].y === yb) return i } return null } function hexGridToCube(grid: Point): Point3 { //even-q layout -> cube layout var z = grid.y - (grid.x + (grid.x & 1)) / 2 var y = -grid.x - z return {x: grid.x, y: y, z: z} } function hexDistance(a: Point, b: Point): number { // we convert our hex coordinates into cube coordinates and then // we only have to see which of the 3 axes is the longest var cubeA = hexGridToCube(a) var cubeB = hexGridToCube(b) return Math.max(Math.abs(cubeA.x - cubeB.x), Math.abs(cubeA.y - cubeB.y), Math.abs(cubeA.z - cubeB.z)) } // Direction between hexes a and b function hexDirectionTo(a: Point, b: Point): number { // TODO: check correctness const delta = {x: b.x - a.x, y: b.y - a.y}; if(delta.x) { const angle = Math.atan2(-delta.y, delta.x) * 180/Math.PI; let temp = 90 - angle|0; if(temp < 0) temp += 360; return Math.min(temp / 60|0, 5); } else if(delta.y < 0) return 0; return 2; } function hexOppositeDirection(direction: number) { return (direction + 3) % 6 } // The adjacent hex around a nearest to b function hexNearestNeighbor(a: Point, b: Point) { var neighbors = hexNeighbors(a) var min = Infinity, minIdx = -1 for(var i = 0; i < neighbors.length; i++) { var dist = hexDistance(neighbors[i], b) if(dist < min) { min = dist minIdx = i } } if(minIdx === -1) return null return {hex: neighbors[minIdx], distance: min, direction: minIdx} } // Draws a line between a and b, returning the list of coordinates (including b) function hexLine(a: Point, b: Point) { var path = [] var position = {x: a.x, y: a.y} while(true) { path.push(position) if(position.x === b.x && position.y === b.y) return path var nearest = hexNearestNeighbor(position, b) if(nearest === null) return null position = nearest.hex } // throw "unreachable" } function hexesInRadius(center: Point, radius: number) { var hexes = [] for(var x = 0; x < 200; x++) { for(var y = 0; y < 200; y++) { if(x === center.x && y === center.y) continue var pos = {x: x, y: y} if(hexDistance(center, pos) <= radius) hexes.push(pos) } } return hexes } function pointInBoundingBox(point: Point, bbox: BoundingBox) { return (bbox.x <= point.x && point.x <= bbox.x+bbox.w && bbox.y <= point.y && point.y <= bbox.y+bbox.h) } function tile_in_tile_rect(tile: Point, a: Point, b: Point, c: Point, d: Point) { //our rect looks like this: //a - - - - b //. . //. . //. . //d - - - - c //or like this: // a // . . // . . //d b // . . // . . // c //these are the only possibilities that give sensical rectangles, // anything else involves guessing of tiles on the borders anyway //if I get the topmost position and check if it's below that //and get the downmost position and check if it's above that //and get the leftmost position and check if it's to the right of that //and the rightmost and check if it's to the left of that //then I do get inside a rect //but not a rect where my points are necessarily corner points. //assumption: well behaved rectangle in a grid //a = min x, min y //b = min x, max y //c = max x, max y //d = max x, min y var error = false if(c.x != d.x || a.x != b.x || a.x > c.x) error = true if(a.y != d.y || b.y != c.y || a.y > c.y) error = true if(error) { console.log("This is not a rectangle: (" + a.x +"," + a.y +"), (" + b.x +"," + b.y +"), (" + c.x +"," + c.y +"), (" + d.x +"," + d.y +")") return false } var inside = true if(tile.x <= a.x || tile.x >= c.x) inside = false if(tile.y <= a.y || tile.y >= c.y) inside = false return inside } function tile_in_tile_rect2(tile: Point, a: Point, c: Point) { var b = {x: a.x, y: c.y} var d = {x: c.x, y: a.y} return tile_in_tile_rect(tile, a, b, c, d) } function pointIntersectsCircle(center: Point, radius: number, point: Point): boolean { return Math.abs(point.x - center.x) <= radius && Math.abs(point.y - center.y) <= radius }
the_stack
import { AccountSet, AccountDelete, CheckCancel, CheckCash, CheckCreate, DepositPreauth, EscrowCancel, EscrowCreate, EscrowFinish, OfferCancel, OfferCreate, PaymentChannelClaim, PaymentChannelCreate, PaymentChannelFund, SetRegularKey, SignerListSet, TrustSet, } from '../../../src/XRP/Generated/web/org/xrpl/rpc/v1/transaction_pb' /* eslint-disable @typescript-eslint/no-magic-numbers -- * ESLint flags the numbers in the Uint8Array as magic numbers, * but this is a fakes file for testing, so it's fine. */ import { ClearFlag, Domain, EmailHash, MessageKey, SetFlag, TransferRate, TickSize, Destination, DestinationTag, CheckID, Amount, DeliverMin, Expiration, SendMax, InvoiceID, Authorize, Unauthorize, Owner, OfferSequence, CancelAfter, FinishAfter, Condition, Fulfillment, TakerGets, TakerPays, Channel, Balance, PaymentChannelSignature, PublicKey, SettleDelay, RegularKey, SignerQuorum, SignerEntry, Account, SignerWeight, LimitAmount, QualityIn, QualityOut, } from '../../../src/XRP/Generated/web/org/xrpl/rpc/v1/common_pb' import { AccountAddress } from '../../../src/XRP/Generated/web/org/xrpl/rpc/v1/account_pb' import { testCurrencyAmountProtoDrops, testCurrencyAmountProtoIssuedCurrency, } from './fake-xrp-protobufs' // Primitive test values =============================================================== // AccountSet values const testClearFlag = 5 const testDomain = 'testdomain' const testEmailHash = new Uint8Array([8, 9, 10]) const testMessageKey = new Uint8Array([11, 12, 13]) const testSetFlag = 4 const testInvalidSetFlag = 5 const testTransferRate = 1234567890 const testInvalidLowTransferRate = 11 const testInvalidHighTransferRate = 9876543210 const testTickSize = 7 const testInvalidTickSize = 27 // AccountDelete values const testDestination = 'rPEPPER7kfTD9w2To4CQk6UCfuHM9c6GDY' const testDestinationTag = 13 const testInvalidDestination = 'badDestination' // CheckCancel values const testCheckId = '49647F0D748DC3FE26BDACBC57F251AADEFFF391403EC9BF87C97F67E9977FB0' // CheckCreate values const testInvoiceId = '6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B' const testExpiration = 570113521 // EscrowCancel values const testOfferSequence = 23 // EscrowCreate values const testCancelAfter = 533257958 const testFinishAfter = 533171558 const testFinishAfterEarly = 533341558 const testCondition = 'A0258020E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855810100' // EscrowFinish values const testFulfillment = 'A0028000' // PaymentChannelClaim values const testChannel = 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198' const testPaymentChannelSignature = '30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1E721B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80ECA3CD7B9B' const testPaymentChannelPublicKey = '32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A' // PaymentChannelCreate values const testSettleDelay = 86400 const testPublicKey = '32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A' // SetRegularKey values const testRegularKey = 'rAR8rR8sUkBoCZFawhkWzY4Y5YoyuznwD' // SignerListSet values const testDestination2 = 'rPuNV4oA6f3SrKA4pLEpdVZW6QLvn3UJxK' const testSignerQuorum = 3 const testSignerWeight = 1 const testSignerQuorumDelete = 0 // TrustSet values const testQualityIn = 5 const testQualityOut = 2 // Protobuf objects ====================================================================== // AccountSet protos const testClearFlagProto = new ClearFlag() testClearFlagProto.setValue(testClearFlag) const testDomainProto = new Domain() testDomainProto.setValue(testDomain) const testEmailHashProto = new EmailHash() testEmailHashProto.setValue(testEmailHash) const testMessageKeyProto = new MessageKey() testMessageKeyProto.setValue(testMessageKey) const testSetFlagProto = new SetFlag() testSetFlagProto.setValue(testSetFlag) const testTransferRateProto = new TransferRate() testTransferRateProto.setValue(testTransferRate) const testTickSizeProto = new TickSize() testTickSizeProto.setValue(testTickSize) const testAccountSetProtoAllFields = new AccountSet() testAccountSetProtoAllFields.setClearFlag(testClearFlagProto) testAccountSetProtoAllFields.setDomain(testDomainProto) testAccountSetProtoAllFields.setEmailHash(testEmailHashProto) testAccountSetProtoAllFields.setMessageKey(testMessageKeyProto) testAccountSetProtoAllFields.setSetFlag(testSetFlagProto) testAccountSetProtoAllFields.setTransferRate(testTransferRateProto) testAccountSetProtoAllFields.setTickSize(testTickSizeProto) const testAccountSetProtoOneFieldSet = new AccountSet() testAccountSetProtoOneFieldSet.setClearFlag(testClearFlagProto) // AccountDelete protos const testAccountAddressProto = new AccountAddress() testAccountAddressProto.setAddress(testDestination) const testDestinationProto = new Destination() testDestinationProto.setValue(testAccountAddressProto) const testDestinationTagProto = new DestinationTag() testDestinationTagProto.setValue(testDestinationTag) const testAccountDeleteProto = new AccountDelete() testAccountDeleteProto.setDestination(testDestinationProto) testAccountDeleteProto.setDestinationTag(testDestinationTagProto) const testAccountDeleteProtoNoTag = new AccountDelete() testAccountDeleteProtoNoTag.setDestination(testDestinationProto) // CheckCancel proto const testCheckIdProto = new CheckID() testCheckIdProto.setValue(testCheckId) const testCheckCancelProto = new CheckCancel() testCheckCancelProto.setCheckId(testCheckIdProto) // CheckCash protos const testAmountProto = new Amount() testAmountProto.setValue(testCurrencyAmountProtoDrops) const testCheckCashProtoWithAmount = new CheckCash() testCheckCashProtoWithAmount.setCheckId(testCheckIdProto) testCheckCashProtoWithAmount.setAmount(testAmountProto) const testDeliverMinProto = new DeliverMin() testDeliverMinProto.setValue(testCurrencyAmountProtoIssuedCurrency) const testCheckCashProtoWithDeliverMin = new CheckCash() testCheckCashProtoWithDeliverMin.setCheckId(testCheckIdProto) testCheckCashProtoWithDeliverMin.setDeliverMin(testDeliverMinProto) // CheckCreate protos const testSendMaxProto = new SendMax() testSendMaxProto.setValue(testCurrencyAmountProtoDrops) const testExpirationProto = new Expiration() testExpirationProto.setValue(testExpiration) const testInvoiceIdProto = new InvoiceID() testInvoiceIdProto.setValue(testInvoiceId) const testCheckCreateProtoAllFields = new CheckCreate() testCheckCreateProtoAllFields.setDestination(testDestinationProto) testCheckCreateProtoAllFields.setSendMax(testSendMaxProto) testCheckCreateProtoAllFields.setDestinationTag(testDestinationTagProto) testCheckCreateProtoAllFields.setExpiration(testExpirationProto) testCheckCreateProtoAllFields.setInvoiceId(testInvoiceIdProto) const testCheckCreateProtoMandatoryFields = new CheckCreate() testCheckCreateProtoMandatoryFields.setDestination(testDestinationProto) testCheckCreateProtoMandatoryFields.setSendMax(testSendMaxProto) // DepositPreauth protos const testAuthorizeProto = new Authorize() testAuthorizeProto.setValue(testAccountAddressProto) const testUnauthorizeProto = new Unauthorize() testUnauthorizeProto.setValue(testAccountAddressProto) const testDepositPreauthProtoSetAuthorize = new DepositPreauth() testDepositPreauthProtoSetAuthorize.setAuthorize(testAuthorizeProto) const testDepositPreauthProtoSetUnauthorize = new DepositPreauth() testDepositPreauthProtoSetUnauthorize.setUnauthorize(testUnauthorizeProto) // EscrowCancel proto const testOwnerProto = new Owner() testOwnerProto.setValue(testAccountAddressProto) const testOfferSequenceProto = new OfferSequence() testOfferSequenceProto.setValue(testOfferSequence) const testEscrowCancelProto = new EscrowCancel() testEscrowCancelProto.setOwner(testOwnerProto) testEscrowCancelProto.setOfferSequence(testOfferSequenceProto) // EscrowCreate protos const testCancelAfterProto = new CancelAfter() testCancelAfterProto.setValue(testCancelAfter) const testFinishAfterProto = new FinishAfter() testFinishAfterProto.setValue(testFinishAfter) const testConditionProto = new Condition() testConditionProto.setValue(testCondition) const testEscrowCreateProtoAllFields = new EscrowCreate() testEscrowCreateProtoAllFields.setAmount(testAmountProto) testEscrowCreateProtoAllFields.setDestination(testDestinationProto) testEscrowCreateProtoAllFields.setCancelAfter(testCancelAfterProto) testEscrowCreateProtoAllFields.setFinishAfter(testFinishAfterProto) testEscrowCreateProtoAllFields.setCondition(testConditionProto) testEscrowCreateProtoAllFields.setDestinationTag(testDestinationTagProto) const testEscrowCreateProtoMandatoryOnly = new EscrowCreate() testEscrowCreateProtoMandatoryOnly.setAmount(testAmountProto) testEscrowCreateProtoMandatoryOnly.setDestination(testDestinationProto) testEscrowCreateProtoMandatoryOnly.setFinishAfter(testFinishAfterProto) // EscrowFinish protos const testFulfillmentProto = new Fulfillment() testFulfillmentProto.setValue(testFulfillment) const testEscrowFinishProtoAllFields = new EscrowFinish() testEscrowFinishProtoAllFields.setOwner(testOwnerProto) testEscrowFinishProtoAllFields.setOfferSequence(testOfferSequenceProto) testEscrowFinishProtoAllFields.setCondition(testConditionProto) testEscrowFinishProtoAllFields.setFulfillment(testFulfillmentProto) const testEscrowFinishProtoMandatoryOnly = new EscrowFinish() testEscrowFinishProtoMandatoryOnly.setOwner(testOwnerProto) testEscrowFinishProtoMandatoryOnly.setOfferSequence(testOfferSequenceProto) // OfferCancel proto const testOfferCancelProto = new OfferCancel() testOfferCancelProto.setOfferSequence(testOfferSequenceProto) // OfferCreate protos const testTakerGetsProto = new TakerGets() testTakerGetsProto.setValue(testCurrencyAmountProtoDrops) const testTakerPaysProto = new TakerPays() testTakerPaysProto.setValue(testCurrencyAmountProtoDrops) const testOfferCreateProtoAllFields = new OfferCreate() testOfferCreateProtoAllFields.setExpiration(testExpirationProto) testOfferCreateProtoAllFields.setOfferSequence(testOfferSequenceProto) testOfferCreateProtoAllFields.setTakerGets(testTakerGetsProto) testOfferCreateProtoAllFields.setTakerPays(testTakerPaysProto) const testOfferCreateProtoMandatoryOnly = new OfferCreate() testOfferCreateProtoMandatoryOnly.setTakerGets(testTakerGetsProto) testOfferCreateProtoMandatoryOnly.setTakerPays(testTakerPaysProto) // PaymentChannelClaim protos const testChannelProto = new Channel() testChannelProto.setValue(testChannel) const testBalanceProto = new Balance() testBalanceProto.setValue(testCurrencyAmountProtoDrops) const testPaymentChannelSignatureProto = new PaymentChannelSignature() testPaymentChannelSignatureProto.setValue(testPaymentChannelSignature) const testPaymentChannelPublicKeyProto = new PublicKey() testPaymentChannelPublicKeyProto.setValue(testPaymentChannelPublicKey) const testPaymentChannelClaimProtoAllFields = new PaymentChannelClaim() testPaymentChannelClaimProtoAllFields.setChannel(testChannelProto) testPaymentChannelClaimProtoAllFields.setBalance(testBalanceProto) testPaymentChannelClaimProtoAllFields.setAmount(testAmountProto) testPaymentChannelClaimProtoAllFields.setPaymentChannelSignature( testPaymentChannelSignatureProto, ) testPaymentChannelClaimProtoAllFields.setPublicKey( testPaymentChannelPublicKeyProto, ) const testPaymentChannelClaimProtoMandatoryOnly = new PaymentChannelClaim() testPaymentChannelClaimProtoMandatoryOnly.setChannel(testChannelProto) // PaymentChannelCreate protos const testSettleDelayProto = new SettleDelay() testSettleDelayProto.setValue(testSettleDelay) const testPublicKeyProto = new PublicKey() testPublicKeyProto.setValue(testPublicKey) const testPaymentChannelCreateProtoAllFields = new PaymentChannelCreate() testPaymentChannelCreateProtoAllFields.setAmount(testAmountProto) testPaymentChannelCreateProtoAllFields.setDestination(testDestinationProto) testPaymentChannelCreateProtoAllFields.setSettleDelay(testSettleDelayProto) testPaymentChannelCreateProtoAllFields.setPublicKey(testPublicKeyProto) testPaymentChannelCreateProtoAllFields.setCancelAfter(testCancelAfterProto) testPaymentChannelCreateProtoAllFields.setDestinationTag( testDestinationTagProto, ) const testPaymentChannelCreateProtoMandatoryOnly = new PaymentChannelCreate() testPaymentChannelCreateProtoMandatoryOnly.setAmount(testAmountProto) testPaymentChannelCreateProtoMandatoryOnly.setDestination(testDestinationProto) testPaymentChannelCreateProtoMandatoryOnly.setSettleDelay(testSettleDelayProto) testPaymentChannelCreateProtoMandatoryOnly.setPublicKey(testPublicKeyProto) // PaymentChannelFund protos const testPaymentChannelFundProtoAllFields = new PaymentChannelFund() testPaymentChannelFundProtoAllFields.setChannel(testChannelProto) testPaymentChannelFundProtoAllFields.setAmount(testAmountProto) testPaymentChannelFundProtoAllFields.setExpiration(testExpirationProto) const testPaymentChannelFundProtoMandatoryOnly = new PaymentChannelFund() testPaymentChannelFundProtoMandatoryOnly.setChannel(testChannelProto) testPaymentChannelFundProtoMandatoryOnly.setAmount(testAmountProto) // SetRegularKey protos const testAccountAddressProtoRegularKey = new AccountAddress() testAccountAddressProtoRegularKey.setAddress(testRegularKey) const testRegularKeyProto = new RegularKey() testRegularKeyProto.setValue(testAccountAddressProtoRegularKey) const testSetRegularKeyProtoWithKey = new SetRegularKey() testSetRegularKeyProtoWithKey.setRegularKey(testRegularKeyProto) const testSetRegularKeyProtoNoKey = new SetRegularKey() // SignerListSet const testSignerQuorumProto = new SignerQuorum() testSignerQuorumProto.setValue(testSignerQuorum) const testSignerQuorumProtoDelete = new SignerQuorum() testSignerQuorumProtoDelete.setValue(testSignerQuorumDelete) const testAccountAddressProto2 = new AccountAddress() testAccountAddressProto2.setAddress(testDestination2) const testAccountProto = new Account() testAccountProto.setValue(testAccountAddressProto) const testAccountProto2 = new Account() testAccountProto2.setValue(testAccountAddressProto2) const testSignerWeightProto = new SignerWeight() testSignerWeightProto.setValue(testSignerWeight) const testSignerEntry1 = new SignerEntry() testSignerEntry1.setAccount(testAccountProto) testSignerEntry1.setSignerWeight(testSignerWeightProto) const testSignerEntry2 = new SignerEntry() testSignerEntry2.setAccount(testAccountProto2) testSignerEntry2.setSignerWeight(testSignerWeightProto) const testSignerEntryList: Array<SignerEntry> = [ testSignerEntry1, testSignerEntry2, ] const testSignerListSetProto = new SignerListSet() testSignerListSetProto.setSignerQuorum(testSignerQuorumProto) testSignerListSetProto.setSignerEntriesList(testSignerEntryList) const testSignerListSetProtoDelete = new SignerListSet() testSignerListSetProtoDelete.setSignerQuorum(testSignerQuorumProtoDelete) testSignerListSetProtoDelete.setSignerEntriesList([] as SignerEntry[]) // TrustSet protos const testLimitAmountProto = new LimitAmount() testLimitAmountProto.setValue(testCurrencyAmountProtoIssuedCurrency) const testQualityInProto = new QualityIn() testQualityInProto.setValue(testQualityIn) const testQualityOutProto = new QualityOut() testQualityOutProto.setValue(testQualityOut) const testTrustSetProtoAllFields = new TrustSet() testTrustSetProtoAllFields.setLimitAmount(testLimitAmountProto) testTrustSetProtoAllFields.setQualityIn(testQualityInProto) testTrustSetProtoAllFields.setQualityOut(testQualityOutProto) const testTrustSetProtoMandatoryOnly = new TrustSet() testTrustSetProtoMandatoryOnly.setLimitAmount(testLimitAmountProto) // Invalid Protobuf Objects ======================================================================== // Invalid AccountSet proto (bad domain) const testInvalidDomainProto = new Domain() testInvalidDomainProto.setValue(testDomain.toUpperCase()) const testInvalidAccountSetProtoBadDomain = new AccountSet() testInvalidAccountSetProtoBadDomain.setDomain(testInvalidDomainProto) // Invalid AccountSet proto (invalid transferRate (too low)) const testInvalidLowTransferRateProto = new TransferRate() testInvalidLowTransferRateProto.setValue(testInvalidLowTransferRate) const testInvalidAccountSetProtoBadLowTransferRate = new AccountSet() testInvalidAccountSetProtoBadLowTransferRate.setTransferRate( testInvalidLowTransferRateProto, ) // Invalid AccountSet proto (invalid transferRate (too high)) const testInvalidHighTransferRateProto = new TransferRate() testInvalidHighTransferRateProto.setValue(testInvalidHighTransferRate) const testInvalidAccountSetProtoBadHighTransferRate = new AccountSet() testInvalidAccountSetProtoBadHighTransferRate.setTransferRate( testInvalidHighTransferRateProto, ) // Invalid AccountSet proto (invalid tickSize) const testInvalidTickSizeProto = new TickSize() testInvalidTickSizeProto.setValue(testInvalidTickSize) const testInvalidAccountSetProtoBadTickSize = new AccountSet() testInvalidAccountSetProtoBadTickSize.setTickSize(testInvalidTickSizeProto) // Invalid AccountSet proto (clearFlag == setFlag) const testInvalidSetFlagProto = new SetFlag() testInvalidSetFlagProto.setValue(testInvalidSetFlag) const testInvalidAccountSetProtoSameSetClearFlag = new AccountSet() testInvalidAccountSetProtoSameSetClearFlag.setClearFlag(testClearFlagProto) testInvalidAccountSetProtoSameSetClearFlag.setSetFlag(testInvalidSetFlagProto) // Invalid AccountDelete proto (bad destination) const testInvalidAccountAddressProto = new AccountAddress() testInvalidAccountAddressProto.setAddress(testInvalidDestination) const testInvalidDestinationProto = new Destination() testInvalidDestinationProto.setValue(testInvalidAccountAddressProto) const testInvalidAccountDeleteProto = new AccountDelete() testInvalidAccountDeleteProto.setDestination(testInvalidDestinationProto) // Invalid CheckCancel proto (missing checkId) const testInvalidCheckCancelProto = new CheckCancel() // Invalid CheckCash proto (missing checkId) const testInvalidCheckCashProtoNoCheckId = new CheckCash() testInvalidCheckCashProtoNoCheckId.setAmount(testAmountProto) // Invalid CheckCash proto (missing both deliverMin and amount) const testInvalidCheckCashProtoNoAmountDeliverMin = new CheckCash() testInvalidCheckCashProtoNoAmountDeliverMin.setCheckId(testCheckIdProto) // Invalid CheckCreate proto (missing destination) const testInvalidCheckCreateProto = new CheckCreate() testInvalidCheckCreateProto.setSendMax(testSendMaxProto) // Invalid CheckCreate proto (bad destination) const testInvalidCheckCreateProtoBadDestination = new CheckCreate() testInvalidCheckCreateProtoBadDestination.setDestination( testInvalidDestinationProto, ) testInvalidCheckCreateProtoBadDestination.setSendMax(testSendMaxProto) // Invalid CheckCreate proto (missing SendMax) const testInvalidCheckCreateProtoNoSendMax = new CheckCreate() testInvalidCheckCreateProtoNoSendMax.setDestination(testDestinationProto) // Invalid DepositPreauth proto (neither authorize nor unauthorize) const testInvalidDepositPreauthProtoNoAuthUnauth = new DepositPreauth() // Invalid DepositPreauth proto (bad authorize) const testInvalidAuthorizeProto = new Authorize() testInvalidAuthorizeProto.setValue(testInvalidAccountAddressProto) const testInvalidUnauthorizeProto = new Unauthorize() testInvalidUnauthorizeProto.setValue(testInvalidAccountAddressProto) const testInvalidDepositPreauthProtoSetBadAuthorize = new DepositPreauth() testInvalidDepositPreauthProtoSetBadAuthorize.setAuthorize( testInvalidAuthorizeProto, ) // Invalid DepositPreauth proto (bad unauthorize) const testInvalidDepositPreauthProtoSetBadUnauthorize = new DepositPreauth() testInvalidDepositPreauthProtoSetBadUnauthorize.setUnauthorize( testInvalidUnauthorizeProto, ) // Invalid EscrowCancel proto (missing owner) const testInvalidEscrowCancelProtoNoOwner = new EscrowCancel() testInvalidEscrowCancelProtoNoOwner.setOfferSequence(testOfferSequenceProto) // Invalid EscrowCancel proto (bad owner) const testInvalidOwnerProto = new Owner() testInvalidOwnerProto.setValue(testInvalidAccountAddressProto) const testInvalidEscrowCancelProtoBadOwner = new EscrowCancel() testInvalidEscrowCancelProtoBadOwner.setOwner(testInvalidOwnerProto) testInvalidEscrowCancelProtoBadOwner.setOfferSequence(testOfferSequenceProto) // Invalid EscrowCancel proto (no offerSequence) const testInvalidEscrowCancelProtoNoOfferSequence = new EscrowCancel() testInvalidEscrowCancelProtoNoOfferSequence.setOwner(testOwnerProto) // Invalid EscrowCreate proto (missing destination) const testInvalidEscrowCreateProtoNoDestination = new EscrowCreate() testInvalidEscrowCreateProtoNoDestination.setAmount(testAmountProto) testInvalidEscrowCreateProtoNoDestination.setFinishAfter(testFinishAfterProto) // Invalid EscrowCreate proto (bad destination) const testInvalidEscrowCreateProtoBadDestination = new EscrowCreate() testInvalidEscrowCreateProtoBadDestination.setAmount(testAmountProto) testInvalidEscrowCreateProtoBadDestination.setDestination( testInvalidDestinationProto, ) testInvalidEscrowCreateProtoBadDestination.setFinishAfter(testFinishAfterProto) // Invalid EscrowCreate proto (no amount) const testInvalidEscrowCreateProtoNoAmount = new EscrowCreate() testInvalidEscrowCreateProtoNoAmount.setDestination(testDestinationProto) testInvalidEscrowCreateProtoNoAmount.setFinishAfter(testFinishAfterProto) // Invalid EscrowCreate proto (no XRP) const testAmountProtoIssuedCurrency = new Amount() testAmountProtoIssuedCurrency.setValue(testCurrencyAmountProtoIssuedCurrency) const testInvalidEscrowCreateProtoNoXRP = new EscrowCreate() testInvalidEscrowCreateProtoNoXRP.setDestination(testDestinationProto) testInvalidEscrowCreateProtoNoXRP.setAmount(testAmountProtoIssuedCurrency) testInvalidEscrowCreateProtoNoXRP.setFinishAfter(testFinishAfterProto) // Invalid EscrowCreate proto (no cancelAfter or finishAfter) const testInvalidEscrowCreateProtoNoCancelFinish = new EscrowCreate() testInvalidEscrowCreateProtoNoCancelFinish.setDestination(testDestinationProto) testInvalidEscrowCreateProtoNoCancelFinish.setAmount(testAmountProto) testInvalidEscrowCreateProtoNoCancelFinish.setCondition(testConditionProto) // Invalid EscrowCreate proto (finishAfter not before cancelAfter) const testFinishAfterProtoEarly = new FinishAfter() testFinishAfterProtoEarly.setValue(testFinishAfterEarly) const testInvalidEscrowCreateProtoBadCancelFinish = new EscrowCreate() testInvalidEscrowCreateProtoBadCancelFinish.setDestination(testDestinationProto) testInvalidEscrowCreateProtoBadCancelFinish.setAmount(testAmountProto) testInvalidEscrowCreateProtoBadCancelFinish.setCondition(testConditionProto) testInvalidEscrowCreateProtoBadCancelFinish.setCancelAfter(testCancelAfterProto) testInvalidEscrowCreateProtoBadCancelFinish.setFinishAfter( testFinishAfterProtoEarly, ) // Invalid EscrowCreate proto (no finishAfter or condition) const testInvalidEscrowCreateProtoNoFinishCondition = new EscrowCreate() testInvalidEscrowCreateProtoNoFinishCondition.setDestination( testDestinationProto, ) testInvalidEscrowCreateProtoNoFinishCondition.setAmount(testAmountProto) testInvalidEscrowCreateProtoNoFinishCondition.setCancelAfter( testCancelAfterProto, ) // Invalid EscrowFinish proto (missing owner) const testInvalidEscrowFinishProtoNoOwner = new EscrowFinish() testInvalidEscrowFinishProtoNoOwner.setOfferSequence(testOfferSequenceProto) // Invalid EscrowFinish proto (bad owner) const testInvalidEscrowFinishProtoBadOwner = new EscrowFinish() testInvalidEscrowFinishProtoBadOwner.setOwner(testInvalidOwnerProto) testInvalidEscrowFinishProtoBadOwner.setOfferSequence(testOfferSequenceProto) // Invalid EscrowFinish proto (missing offerSequence) const testInvalidEscrowFinishProtoNoOfferSequence = new EscrowFinish() testInvalidEscrowFinishProtoNoOfferSequence.setOwner(testOwnerProto) // Invalid OfferCancel proto (missing offerSequence) const testInvalidOfferCancelProto = new OfferCancel() // Invalid OfferCreate proto (missing takerGets) const testInvalidOfferCreateProtoNoTakerGets = new OfferCreate() testInvalidOfferCreateProtoNoTakerGets.setTakerPays(testTakerPaysProto) // Invalid OfferCreate proto (missing takerPays) const testInvalidOfferCreateProtoNoTakerPays = new OfferCreate() testInvalidOfferCreateProtoNoTakerPays.setTakerGets(testTakerGetsProto) // Invalid PaymentChannelClaim proto (missing channel) const testInvalidPaymentChannelClaimProtoNoChannel = new PaymentChannelClaim() // Invalid PaymentChannelClaim proto (missing publicKey with signature) const testInvalidPaymentChannelClaimProtoSignatureNoPublicKey = new PaymentChannelClaim() testInvalidPaymentChannelClaimProtoSignatureNoPublicKey.setChannel( testChannelProto, ) testInvalidPaymentChannelClaimProtoSignatureNoPublicKey.setBalance( testBalanceProto, ) testInvalidPaymentChannelClaimProtoSignatureNoPublicKey.setAmount( testAmountProto, ) testInvalidPaymentChannelClaimProtoSignatureNoPublicKey.setPaymentChannelSignature( testPaymentChannelSignatureProto, ) // Invalid PaymentChannelCreate proto (missing amount) const testInvalidPaymentChannelCreateProtoNoAmount = new PaymentChannelCreate() testInvalidPaymentChannelCreateProtoNoAmount.setDestination( testDestinationProto, ) testInvalidPaymentChannelCreateProtoNoAmount.setSettleDelay( testSettleDelayProto, ) testInvalidPaymentChannelCreateProtoNoAmount.setPublicKey(testPublicKeyProto) // Invalid PaymentChannelCreate proto (missing destination) const testInvalidPaymentChannelCreateProtoNoDestination = new PaymentChannelCreate() testInvalidPaymentChannelCreateProtoNoDestination.setAmount(testAmountProto) testInvalidPaymentChannelCreateProtoNoDestination.setSettleDelay( testSettleDelayProto, ) testInvalidPaymentChannelCreateProtoNoDestination.setPublicKey( testPublicKeyProto, ) // Invalid PaymentChannelCreate proto (bad destination) const testInvalidPaymentChannelCreateProtoBadDestination = new PaymentChannelCreate() testInvalidPaymentChannelCreateProtoBadDestination.setAmount(testAmountProto) testInvalidPaymentChannelCreateProtoBadDestination.setDestination( testInvalidDestinationProto, ) testInvalidPaymentChannelCreateProtoBadDestination.setSettleDelay( testSettleDelayProto, ) testInvalidPaymentChannelCreateProtoBadDestination.setPublicKey( testPublicKeyProto, ) // Invalid PaymentChannelCreate proto (missing settleDelay) const testInvalidPaymentChannelCreateProtoNoSettleDelay = new PaymentChannelCreate() testInvalidPaymentChannelCreateProtoNoSettleDelay.setAmount(testAmountProto) testInvalidPaymentChannelCreateProtoNoSettleDelay.setDestination( testDestinationProto, ) testInvalidPaymentChannelCreateProtoNoSettleDelay.setPublicKey( testPublicKeyProto, ) // Invalid PaymentChannelCreate proto (missing publicKey) const testInvalidPaymentChannelCreateProtoNoPublicKey = new PaymentChannelCreate() testInvalidPaymentChannelCreateProtoNoPublicKey.setAmount(testAmountProto) testInvalidPaymentChannelCreateProtoNoPublicKey.setDestination( testDestinationProto, ) testInvalidPaymentChannelCreateProtoNoPublicKey.setSettleDelay( testSettleDelayProto, ) // Invalid PaymentChannelFund proto (missing amount) const testInvalidPaymentChannelFundProtoNoAmount = new PaymentChannelFund() testInvalidPaymentChannelFundProtoNoAmount.setChannel(testChannelProto) // Invalid PaymentChannelFund proto (missing channel) const testInvalidPaymentChannelFundProtoNoChannel = new PaymentChannelFund() testInvalidPaymentChannelFundProtoNoChannel.setAmount(testAmountProto) // Invalid SignerListSet proto (missing SignerQuorum) const testInvalidSignerListSetProtoNoSignerQuorum = new SignerListSet() testInvalidSignerListSetProtoNoSignerQuorum.setSignerEntriesList( testSignerEntryList, ) // Invalid SignerListSet proto (missing SignerEntries) const testInvalidSignerListSetProtoNoSignerEntries = new SignerListSet() testInvalidSignerListSetProtoNoSignerEntries.setSignerQuorum( testSignerQuorumProto, ) // Invalid SignerListSet proto (too many elements in SignerEntries) const testInvalidSignerEntryListProtoTooManyElements: Array<SignerEntry> = [ testSignerEntry1, testSignerEntry2, testSignerEntry1, testSignerEntry2, testSignerEntry1, testSignerEntry2, testSignerEntry1, testSignerEntry2, testSignerEntry1, testSignerEntry2, ] const testInvalidSignerListSetProtoTooManySignerEntries = new SignerListSet() testInvalidSignerListSetProtoTooManySignerEntries.setSignerQuorum( testSignerQuorumProto, ) testInvalidSignerListSetProtoTooManySignerEntries.setSignerEntriesList( testInvalidSignerEntryListProtoTooManyElements, ) // Invalid SignerListSet proto (too many elements in SignerEntries) const testInvalidSignerEntryListRepeatAddresses: Array<SignerEntry> = [ testSignerEntry1, testSignerEntry2, testSignerEntry1, testSignerEntry2, ] const testInvalidSignerListSetProtoRepeatAddresses = new SignerListSet() testInvalidSignerListSetProtoRepeatAddresses.setSignerQuorum( testSignerQuorumProto, ) testInvalidSignerListSetProtoRepeatAddresses.setSignerEntriesList( testInvalidSignerEntryListRepeatAddresses, ) // Invalid TrustSet proto (missing limitAmount) const testInvalidTrustSetProto = new TrustSet() testInvalidTrustSetProto.setQualityIn(testQualityInProto) testInvalidTrustSetProto.setQualityOut(testQualityOutProto) // Invalid TrustSet proto (limitAmount uses XRP) const testInvalidLimitAmountProto = new LimitAmount() testInvalidLimitAmountProto.setValue(testCurrencyAmountProtoDrops) const testInvalidTrustSetProtoXRP = new TrustSet() testInvalidTrustSetProtoXRP.setLimitAmount(testInvalidLimitAmountProto) export { testAccountSetProtoAllFields, testAccountSetProtoOneFieldSet, testAccountDeleteProto, testAccountDeleteProtoNoTag, testCheckCancelProto, testCheckCashProtoWithAmount, testCheckCashProtoWithDeliverMin, testCheckCreateProtoAllFields, testCheckCreateProtoMandatoryFields, testDepositPreauthProtoSetAuthorize, testDepositPreauthProtoSetUnauthorize, testEscrowCancelProto, testEscrowCreateProtoAllFields, testEscrowCreateProtoMandatoryOnly, testEscrowFinishProtoAllFields, testEscrowFinishProtoMandatoryOnly, testOfferCancelProto, testOfferCreateProtoAllFields, testOfferCreateProtoMandatoryOnly, testPaymentChannelClaimProtoAllFields, testPaymentChannelClaimProtoMandatoryOnly, testPaymentChannelCreateProtoAllFields, testPaymentChannelCreateProtoMandatoryOnly, testPaymentChannelFundProtoAllFields, testPaymentChannelFundProtoMandatoryOnly, testSetRegularKeyProtoWithKey, testSetRegularKeyProtoNoKey, testSignerEntry1, testSignerEntry2, testSignerListSetProto, testSignerListSetProtoDelete, testTrustSetProtoAllFields, testTrustSetProtoMandatoryOnly, testInvalidAccountSetProtoBadDomain, testInvalidAccountSetProtoBadLowTransferRate, testInvalidAccountSetProtoBadHighTransferRate, testInvalidAccountSetProtoBadTickSize, testInvalidAccountSetProtoSameSetClearFlag, testInvalidAccountDeleteProto, testInvalidCheckCancelProto, testInvalidCheckCashProtoNoCheckId, testInvalidCheckCashProtoNoAmountDeliverMin, testInvalidCheckCreateProto, testInvalidCheckCreateProtoBadDestination, testInvalidCheckCreateProtoNoSendMax, testInvalidDepositPreauthProtoNoAuthUnauth, testInvalidDepositPreauthProtoSetBadAuthorize, testInvalidDepositPreauthProtoSetBadUnauthorize, testInvalidEscrowCancelProtoNoOwner, testInvalidEscrowCancelProtoBadOwner, testInvalidEscrowCancelProtoNoOfferSequence, testInvalidEscrowCreateProtoNoDestination, testInvalidEscrowCreateProtoBadDestination, testInvalidEscrowCreateProtoNoAmount, testInvalidEscrowCreateProtoBadCancelFinish, testInvalidEscrowCreateProtoNoCancelFinish, testInvalidEscrowCreateProtoNoFinishCondition, testInvalidEscrowCreateProtoNoXRP, testInvalidEscrowFinishProtoNoOwner, testInvalidEscrowFinishProtoBadOwner, testInvalidEscrowFinishProtoNoOfferSequence, testInvalidOfferCancelProto, testInvalidOfferCreateProtoNoTakerGets, testInvalidOfferCreateProtoNoTakerPays, testInvalidPaymentChannelClaimProtoNoChannel, testInvalidPaymentChannelClaimProtoSignatureNoPublicKey, testInvalidPaymentChannelCreateProtoNoAmount, testInvalidPaymentChannelCreateProtoNoDestination, testInvalidPaymentChannelCreateProtoBadDestination, testInvalidPaymentChannelCreateProtoNoSettleDelay, testInvalidPaymentChannelCreateProtoNoPublicKey, testInvalidPaymentChannelFundProtoNoAmount, testInvalidPaymentChannelFundProtoNoChannel, testInvalidSignerListSetProtoNoSignerQuorum, testInvalidSignerListSetProtoNoSignerEntries, testInvalidSignerListSetProtoTooManySignerEntries, testInvalidSignerListSetProtoRepeatAddresses, testInvalidTrustSetProto, testInvalidTrustSetProtoXRP, }
the_stack
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { AbstractClient } from "../../../common/abstract_client" import { ClientConfig } from "../../../common/interface" import { SetTrafficMirrorHealthSwitchRequest, SetTrafficMirrorAliasResponse, DeleteL7RulesRequest, DeleteTrafficMirrorResponse, ModifyL7BackendPortResponse, ModifyL4BackendProbePortResponse, BindTrafficMirrorReceiver, ModifyL4BackendPortResponse, ModifyL7LocationsResponse, DescribeTrafficMirrorReceiverHealthStatusRequest, UnbindL4Backend, ModifyL4ListenerResponse, DevicesBindInfoL4Listener, DescribeL4ListenerInfoRequest, L4ListenerInfo, DescribeL7RulesRequest, UnbindL7BackendsResponse, ModifyL4BackendWeightResponse, DeleteL7DomainsResponse, DevicesBindInfoBackend, UnbindL4BackendsRequest, DescribeL7ListenersRequest, DescribeTrafficMirrorListenersRequest, BindL7Backend, ModifyL7ListenerResponse, DescribeLoadBalancerTaskResultRequest, DescribeL7RulesResponse, CreateTrafficMirrorResponse, DescribeDevicesBindInfoRequest, BindL4BackendsResponse, TrafficMirrorListener, DescribeL7ListenersExResponse, UnbindL7Backend, TrafficMirrorReceiver, TrafficMirrorPortStatus, UploadCertResponse, DescribeTrafficMirrorReceiversResponse, DeleteListenersRequest, ModifyL4BackendProbePortRequest, DescribeTrafficMirrorsRequest, UploadCertRequest, DescribeL4ListenerInfoResponse, BindTrafficMirrorListenersRequest, ModifyL7BackendPortRequest, ModifyL4BackendPortRequest, DescribeL4ListenersResponse, ModifyL7LocationsRequest, ModifyLoadBalancerResponse, CreateL4ListenersResponse, ModifyL7BackendWeightResponse, DescribeTrafficMirrorsResponse, DescribeL7BackendsRequest, L7Listener, CreateL7RulesRequest, ModifyL7BackendWeightRequest, CreateL4ListenersRequest, ReplaceCertRequest, BindL7BackendsResponse, L7Rule, UnbindTrafficMirrorReceiversResponse, DeleteL7DomainsRequest, BindTrafficMirrorReceiversRequest, BindTrafficMirrorListenersResponse, BindL7BackendsRequest, DescribeL4Backend, DescribeCertDetailResponse, DescribeL4BackendsRequest, DescribeTrafficMirrorReceiverHealthStatusResponse, BindTrafficMirrorReceiversResponse, ReplaceCertResponse, DescribeLoadBalancerPortInfoRequest, DevicesBindInfoLocation, SetTrafficMirrorHealthSwitchResponse, DeleteLoadBalancerRequest, UnbindTrafficMirrorListenersResponse, CreateL7Rule, CreateL7RulesResponse, ModifyL7ListenerRequest, DescribeTrafficMirrorReceiver, L7ExListener, L7ListenerInfo, L7ListenerInfoRule, DescribeL7BackendsResponse, Filter, DevicesBindInfoRule, TrafficMirror, DescribeLoadBalancersRequest, DevicesBindInfoLoadBalancer, L4Listener, CreateL7Listener, DeleteLoadBalancerResponse, CreateTrafficMirrorRequest, BindL4BackendsRequest, DescribeL7ListenerInfoResponse, DescribeL7ListenersResponse, DeleteListenersResponse, CreateLoadBalancersResponse, UnbindTrafficMirrorReceiver, ModifyLoadBalancerChargeModeResponse, UnbindL7BackendsRequest, L7ListenerInfoLocation, L7RulesLocation, ModifyLoadBalancerChargeModeListener, TrafficMirrorReciversStatus, CreateLoadBalancersRequest, DescribeLoadBalancerPortInfoResponse, DescribeL7ListenerInfoRequest, ModifyL4ListenerRequest, L4Backend, L7Backend, ModifyL7LocationRule, ModifyLoadBalancerRequest, DevicesBindInfoL7Listener, DescribeL4ListenersRequest, CreateL7ListenersResponse, CreateLoadBalancerBzConf, DeleteTrafficMirrorRequest, CreateL7ListenersRequest, BindL4Backend, DescribeL7ListenersExRequest, DescribeLoadBalancerTaskResultResponse, UnbindTrafficMirrorReceiversRequest, UnbindTrafficMirrorListenersRequest, DescribeCertDetailRequest, DescribeDevicesBindInfoResponse, LoadBalancerPortInfoListener, DescribeL4BackendsResponse, CreateL4Listener, DescribeTrafficMirrorListenersResponse, DescribeLoadBalancersResponse, DeleteL7RulesResponse, CertDetailLoadBalancer, DescribeTrafficMirrorReceiversRequest, SetTrafficMirrorAliasRequest, UnbindL4BackendsResponse, L7ListenerInfoBackend, ModifyLoadBalancerChargeModeRequest, ModifyL4BackendWeightRequest, LoadBalancer, } from "./bmlb_models" /** * bmlb client * @class */ export class Client extends AbstractClient { constructor(clientConfig: ClientConfig) { super("bmlb.tencentcloudapi.com", "2018-06-25", clientConfig) } /** * 获取黑石负载均衡七层监听器列表信息。 */ async DescribeL7Listeners( req: DescribeL7ListenersRequest, cb?: (error: string, rep: DescribeL7ListenersResponse) => void ): Promise<DescribeL7ListenersResponse> { return this.request("DescribeL7Listeners", req, cb) } /** * 从流量镜像实例上解绑流量镜像接收机。 */ async UnbindTrafficMirrorReceivers( req: UnbindTrafficMirrorReceiversRequest, cb?: (error: string, rep: UnbindTrafficMirrorReceiversResponse) => void ): Promise<UnbindTrafficMirrorReceiversResponse> { return this.request("UnbindTrafficMirrorReceivers", req, cb) } /** * 修改黑石负载均衡七层转发路径后端实例权重。 */ async ModifyL7BackendWeight( req: ModifyL7BackendWeightRequest, cb?: (error: string, rep: ModifyL7BackendWeightResponse) => void ): Promise<ModifyL7BackendWeightResponse> { return this.request("ModifyL7BackendWeight", req, cb) } /** * 修改黑石负载均衡四层监听器后端实例权重功能。 */ async ModifyL4BackendWeight( req: ModifyL4BackendWeightRequest, cb?: (error: string, rep: ModifyL4BackendWeightResponse) => void ): Promise<ModifyL4BackendWeightResponse> { return this.request("ModifyL4BackendWeight", req, cb) } /** * 创建黑石四层负载均衡监听器功能。黑石负载均衡四层监听器提供了转发用户请求的具体规则,包括端口、协议、会话保持、健康检查等参数。 */ async CreateL4Listeners( req: CreateL4ListenersRequest, cb?: (error: string, rep: CreateL4ListenersResponse) => void ): Promise<CreateL4ListenersResponse> { return this.request("CreateL4Listeners", req, cb) } /** * 解绑黑石负载均衡四层监听器物理服务器。 */ async UnbindL4Backends( req: UnbindL4BackendsRequest, cb?: (error: string, rep: UnbindL4BackendsResponse) => void ): Promise<UnbindL4BackendsResponse> { return this.request("UnbindL4Backends", req, cb) } /** * 修改黑石负载均衡七层监听器。 */ async ModifyL7Listener( req: ModifyL7ListenerRequest, cb?: (error: string, rep: ModifyL7ListenerResponse) => void ): Promise<ModifyL7ListenerResponse> { return this.request("ModifyL7Listener", req, cb) } /** * 删除已创建的黑石流量镜像实例,删除过程是异步执行的,因此需要使用查询任务接口获取删除的结果。 */ async DeleteTrafficMirror( req: DeleteTrafficMirrorRequest, cb?: (error: string, rep: DeleteTrafficMirrorResponse) => void ): Promise<DeleteTrafficMirrorResponse> { return this.request("DeleteTrafficMirror", req, cb) } /** * 创建黑石负载均衡七层转发规则。 */ async CreateL7Rules( req: CreateL7RulesRequest, cb?: (error: string, rep: CreateL7RulesResponse) => void ): Promise<CreateL7RulesResponse> { return this.request("CreateL7Rules", req, cb) } /** * 获取流量镜像接收机健康状态。 */ async DescribeTrafficMirrorReceiverHealthStatus( req: DescribeTrafficMirrorReceiverHealthStatusRequest, cb?: (error: string, rep: DescribeTrafficMirrorReceiverHealthStatusResponse) => void ): Promise<DescribeTrafficMirrorReceiverHealthStatusResponse> { return this.request("DescribeTrafficMirrorReceiverHealthStatus", req, cb) } /** * 解绑黑石物理服务器或者托管服务器到七层转发路径功能。 */ async UnbindL7Backends( req: UnbindL7BackendsRequest, cb?: (error: string, rep: UnbindL7BackendsResponse) => void ): Promise<UnbindL7BackendsResponse> { return this.request("UnbindL7Backends", req, cb) } /** * 删除黑石负载均衡七层转发规则。 */ async DeleteL7Rules( req: DeleteL7RulesRequest, cb?: (error: string, rep: DeleteL7RulesResponse) => void ): Promise<DeleteL7RulesResponse> { return this.request("DeleteL7Rules", req, cb) } /** * 查找绑定了某主机或者指定监听器名称的黑石负载均衡四层监听器。 */ async DescribeL4ListenerInfo( req: DescribeL4ListenerInfoRequest, cb?: (error: string, rep: DescribeL4ListenerInfoResponse) => void ): Promise<DescribeL4ListenerInfoResponse> { return this.request("DescribeL4ListenerInfo", req, cb) } /** * 获取流量镜像的监听器列表信息。 */ async DescribeTrafficMirrorListeners( req: DescribeTrafficMirrorListenersRequest, cb?: (error: string, rep: DescribeTrafficMirrorListenersResponse) => void ): Promise<DescribeTrafficMirrorListenersResponse> { return this.request("DescribeTrafficMirrorListeners", req, cb) } /** * 修改黑石负载均衡七层转发路径。 */ async ModifyL7Locations( req: ModifyL7LocationsRequest, cb?: (error: string, rep: ModifyL7LocationsResponse) => void ): Promise<ModifyL7LocationsResponse> { return this.request("ModifyL7Locations", req, cb) } /** * 修改黑石负载均衡四层监听器后端实例端口。 */ async ModifyL4BackendPort( req: ModifyL4BackendPortRequest, cb?: (error: string, rep: ModifyL4BackendPortResponse) => void ): Promise<ModifyL4BackendPortResponse> { return this.request("ModifyL4BackendPort", req, cb) } /** * 删除用户指定的黑石负载均衡实例。 */ async DeleteLoadBalancer( req: DeleteLoadBalancerRequest, cb?: (error: string, rep: DeleteLoadBalancerResponse) => void ): Promise<DeleteLoadBalancerResponse> { return this.request("DeleteLoadBalancer", req, cb) } /** * 用来创建黑石负载均衡。为了使用黑石负载均衡服务,您必须要创建一个或者多个负载均衡实例。通过成功调用该接口,会返回负载均衡实例的唯一ID。用户可以购买的黑石负载均衡实例类型分为:公网类型、内网类型。公网类型负载均衡对应一个BGP VIP,可用于快速访问公网负载均衡绑定的物理服务器;内网类型负载均衡对应一个腾讯云内部的VIP,不能通过Internet访问,可快速访问内网负载均衡绑定的物理服务器。 */ async CreateLoadBalancers( req: CreateLoadBalancersRequest, cb?: (error: string, rep: CreateLoadBalancersResponse) => void ): Promise<CreateLoadBalancersResponse> { return this.request("CreateLoadBalancers", req, cb) } /** * 获取黑石负载均衡七层转发规则。 */ async DescribeL7Rules( req: DescribeL7RulesRequest, cb?: (error: string, rep: DescribeL7RulesResponse) => void ): Promise<DescribeL7RulesResponse> { return this.request("DescribeL7Rules", req, cb) } /** * 查询负载均衡实例异步任务的执行情况。 */ async DescribeLoadBalancerTaskResult( req: DescribeLoadBalancerTaskResultRequest, cb?: (error: string, rep: DescribeLoadBalancerTaskResultResponse) => void ): Promise<DescribeLoadBalancerTaskResultResponse> { return this.request("DescribeLoadBalancerTaskResult", req, cb) } /** * 查找绑定了某主机或者有某转发域名黑石负载均衡七层监听器。 */ async DescribeL7ListenerInfo( req: DescribeL7ListenerInfoRequest, cb?: (error: string, rep: DescribeL7ListenerInfoResponse) => void ): Promise<DescribeL7ListenerInfoResponse> { return this.request("DescribeL7ListenerInfo", req, cb) } /** * 获取黑石负载均衡四层监听器。 */ async DescribeL4Listeners( req: DescribeL4ListenersRequest, cb?: (error: string, rep: DescribeL4ListenersResponse) => void ): Promise<DescribeL4ListenersResponse> { return this.request("DescribeL4Listeners", req, cb) } /** * 设置流量镜像的健康检查参数。 */ async SetTrafficMirrorHealthSwitch( req: SetTrafficMirrorHealthSwitchRequest, cb?: (error: string, rep: SetTrafficMirrorHealthSwitchResponse) => void ): Promise<SetTrafficMirrorHealthSwitchResponse> { return this.request("SetTrafficMirrorHealthSwitch", req, cb) } /** * 获取黑石负载均衡实例列表 */ async DescribeLoadBalancers( req: DescribeLoadBalancersRequest, cb?: (error: string, rep: DescribeLoadBalancersResponse) => void ): Promise<DescribeLoadBalancersResponse> { return this.request("DescribeLoadBalancers", req, cb) } /** * 删除黑石负载均衡监听器。 */ async DeleteListeners( req: DeleteListenersRequest, cb?: (error: string, rep: DeleteListenersResponse) => void ): Promise<DeleteListenersResponse> { return this.request("DeleteListeners", req, cb) } /** * 获取黑石负载均衡证书详情。 */ async DescribeCertDetail( req: DescribeCertDetailRequest, cb?: (error: string, rep: DescribeCertDetailResponse) => void ): Promise<DescribeCertDetailResponse> { return this.request("DescribeCertDetail", req, cb) } /** * 解绑流量镜像监听器。 */ async UnbindTrafficMirrorListeners( req: UnbindTrafficMirrorListenersRequest, cb?: (error: string, rep: UnbindTrafficMirrorListenersResponse) => void ): Promise<UnbindTrafficMirrorListenersResponse> { return this.request("UnbindTrafficMirrorListeners", req, cb) } /** * 修改黑石负载均衡七层转发路径后端实例端口。 */ async ModifyL7BackendPort( req: ModifyL7BackendPortRequest, cb?: (error: string, rep: ModifyL7BackendPortResponse) => void ): Promise<ModifyL7BackendPortResponse> { return this.request("ModifyL7BackendPort", req, cb) } /** * 获取黑石负载均衡七层监听器绑定的主机列表 */ async DescribeL7Backends( req: DescribeL7BackendsRequest, cb?: (error: string, rep: DescribeL7BackendsResponse) => void ): Promise<DescribeL7BackendsResponse> { return this.request("DescribeL7Backends", req, cb) } /** * 创建流量镜像实例。 */ async CreateTrafficMirror( req: CreateTrafficMirrorRequest, cb?: (error: string, rep: CreateTrafficMirrorResponse) => void ): Promise<CreateTrafficMirrorResponse> { return this.request("CreateTrafficMirror", req, cb) } /** * 修改黑石负载均衡四层监听器后端探测端口。 */ async ModifyL4BackendProbePort( req: ModifyL4BackendProbePortRequest, cb?: (error: string, rep: ModifyL4BackendProbePortResponse) => void ): Promise<ModifyL4BackendProbePortResponse> { return this.request("ModifyL4BackendProbePort", req, cb) } /** * 绑定黑石服务器到四层监听器。服务器包括物理服务器、虚拟机以及半托管机器。 */ async BindL4Backends( req: BindL4BackendsRequest, cb?: (error: string, rep: BindL4BackendsResponse) => void ): Promise<BindL4BackendsResponse> { return this.request("BindL4Backends", req, cb) } /** * 绑定黑石物理服务器成为流量镜像接收机。 */ async BindTrafficMirrorReceivers( req: BindTrafficMirrorReceiversRequest, cb?: (error: string, rep: BindTrafficMirrorReceiversResponse) => void ): Promise<BindTrafficMirrorReceiversResponse> { return this.request("BindTrafficMirrorReceivers", req, cb) } /** * 更新黑石负载均衡证书。 */ async ReplaceCert( req: ReplaceCertRequest, cb?: (error: string, rep: ReplaceCertResponse) => void ): Promise<ReplaceCertResponse> { return this.request("ReplaceCert", req, cb) } /** * 删除黑石负载均衡七层转发域名。 */ async DeleteL7Domains( req: DeleteL7DomainsRequest, cb?: (error: string, rep: DeleteL7DomainsResponse) => void ): Promise<DeleteL7DomainsResponse> { return this.request("DeleteL7Domains", req, cb) } /** * 获取流量镜像实例的列表信息。 */ async DescribeTrafficMirrors( req: DescribeTrafficMirrorsRequest, cb?: (error: string, rep: DescribeTrafficMirrorsResponse) => void ): Promise<DescribeTrafficMirrorsResponse> { return this.request("DescribeTrafficMirrors", req, cb) } /** * 获取指定VPC下的7层监听器(支持模糊匹配)。 */ async DescribeL7ListenersEx( req: DescribeL7ListenersExRequest, cb?: (error: string, rep: DescribeL7ListenersExResponse) => void ): Promise<DescribeL7ListenersExResponse> { return this.request("DescribeL7ListenersEx", req, cb) } /** * 创建黑石负载均衡证书。 */ async UploadCert( req: UploadCertRequest, cb?: (error: string, rep: UploadCertResponse) => void ): Promise<UploadCertResponse> { return this.request("UploadCert", req, cb) } /** * 绑定黑石物理服务器或半托管服务器到七层转发路径。 */ async BindL7Backends( req: BindL7BackendsRequest, cb?: (error: string, rep: BindL7BackendsResponse) => void ): Promise<BindL7BackendsResponse> { return this.request("BindL7Backends", req, cb) } /** * 获取黑石负载均衡四层监听器绑定的主机列表。 */ async DescribeL4Backends( req: DescribeL4BackendsRequest, cb?: (error: string, rep: DescribeL4BackendsResponse) => void ): Promise<DescribeL4BackendsResponse> { return this.request("DescribeL4Backends", req, cb) } /** * 绑定黑石服务器七层监听器到流量镜像实例。 */ async BindTrafficMirrorListeners( req: BindTrafficMirrorListenersRequest, cb?: (error: string, rep: BindTrafficMirrorListenersResponse) => void ): Promise<BindTrafficMirrorListenersResponse> { return this.request("BindTrafficMirrorListeners", req, cb) } /** * 根据输入参数来修改黑石负载均衡实例的基本配置信息。可能的信息包括负载均衡实例的名称,域名前缀。 */ async ModifyLoadBalancer( req: ModifyLoadBalancerRequest, cb?: (error: string, rep: ModifyLoadBalancerResponse) => void ): Promise<ModifyLoadBalancerResponse> { return this.request("ModifyLoadBalancer", req, cb) } /** * 设置流量镜像的别名。 */ async SetTrafficMirrorAlias( req: SetTrafficMirrorAliasRequest, cb?: (error: string, rep: SetTrafficMirrorAliasResponse) => void ): Promise<SetTrafficMirrorAliasResponse> { return this.request("SetTrafficMirrorAlias", req, cb) } /** * 获取黑石负载均衡端口相关信息。 */ async DescribeLoadBalancerPortInfo( req: DescribeLoadBalancerPortInfoRequest, cb?: (error: string, rep: DescribeLoadBalancerPortInfoResponse) => void ): Promise<DescribeLoadBalancerPortInfoResponse> { return this.request("DescribeLoadBalancerPortInfo", req, cb) } /** * 更改黑石负载均衡的计费方式 */ async ModifyLoadBalancerChargeMode( req: ModifyLoadBalancerChargeModeRequest, cb?: (error: string, rep: ModifyLoadBalancerChargeModeResponse) => void ): Promise<ModifyLoadBalancerChargeModeResponse> { return this.request("ModifyLoadBalancerChargeMode", req, cb) } /** * 创建黑石负载均衡七层监听器功能。负载均衡七层监听器提供了转发用户请求的具体规则,包括端口、协议等参数。 */ async CreateL7Listeners( req: CreateL7ListenersRequest, cb?: (error: string, rep: CreateL7ListenersResponse) => void ): Promise<CreateL7ListenersResponse> { return this.request("CreateL7Listeners", req, cb) } /** * 查询黑石物理机和虚机以及托管服务器绑定的黑石负载均衡详情。 */ async DescribeDevicesBindInfo( req: DescribeDevicesBindInfoRequest, cb?: (error: string, rep: DescribeDevicesBindInfoResponse) => void ): Promise<DescribeDevicesBindInfoResponse> { return this.request("DescribeDevicesBindInfo", req, cb) } /** * 修改黑石负载均衡四层监听器。 */ async ModifyL4Listener( req: ModifyL4ListenerRequest, cb?: (error: string, rep: ModifyL4ListenerResponse) => void ): Promise<ModifyL4ListenerResponse> { return this.request("ModifyL4Listener", req, cb) } /** * 获取指定流量镜像实例的接收机信息。 */ async DescribeTrafficMirrorReceivers( req: DescribeTrafficMirrorReceiversRequest, cb?: (error: string, rep: DescribeTrafficMirrorReceiversResponse) => void ): Promise<DescribeTrafficMirrorReceiversResponse> { return this.request("DescribeTrafficMirrorReceivers", req, cb) } }
the_stack
namespace dragonBones { /** * @private */ export class BinaryDataParser extends ObjectDataParser { private _binaryOffset: number; private _binary: ArrayBuffer; private _intArrayBuffer: Int16Array; private _frameArrayBuffer: Int16Array; private _timelineArrayBuffer: Uint16Array; private _inRange(a: number, min: number, max: number): boolean { return min <= a && a <= max; } private _decodeUTF8(data: Uint8Array): string { const EOF_byte = -1; const EOF_code_point = -1; const FATAL_POINT = 0xFFFD; let pos = 0; let result = ""; let code_point; let utf8_code_point = 0; let utf8_bytes_needed = 0; let utf8_bytes_seen = 0; let utf8_lower_boundary = 0; while (data.length > pos) { let _byte = data[pos++]; if (_byte === EOF_byte) { if (utf8_bytes_needed !== 0) { code_point = FATAL_POINT; } else { code_point = EOF_code_point; } } else { if (utf8_bytes_needed === 0) { if (this._inRange(_byte, 0x00, 0x7F)) { code_point = _byte; } else { if (this._inRange(_byte, 0xC2, 0xDF)) { utf8_bytes_needed = 1; utf8_lower_boundary = 0x80; utf8_code_point = _byte - 0xC0; } else if (this._inRange(_byte, 0xE0, 0xEF)) { utf8_bytes_needed = 2; utf8_lower_boundary = 0x800; utf8_code_point = _byte - 0xE0; } else if (this._inRange(_byte, 0xF0, 0xF4)) { utf8_bytes_needed = 3; utf8_lower_boundary = 0x10000; utf8_code_point = _byte - 0xF0; } else { } utf8_code_point = utf8_code_point * Math.pow(64, utf8_bytes_needed); code_point = null; } } else if (!this._inRange(_byte, 0x80, 0xBF)) { utf8_code_point = 0; utf8_bytes_needed = 0; utf8_bytes_seen = 0; utf8_lower_boundary = 0; pos--; code_point = _byte; } else { utf8_bytes_seen += 1; utf8_code_point = utf8_code_point + (_byte - 0x80) * Math.pow(64, utf8_bytes_needed - utf8_bytes_seen); if (utf8_bytes_seen !== utf8_bytes_needed) { code_point = null; } else { let cp = utf8_code_point; let lower_boundary = utf8_lower_boundary; utf8_code_point = 0; utf8_bytes_needed = 0; utf8_bytes_seen = 0; utf8_lower_boundary = 0; if (this._inRange(cp, lower_boundary, 0x10FFFF) && !this._inRange(cp, 0xD800, 0xDFFF)) { code_point = cp; } else { code_point = _byte; } } } } //Decode string if (code_point !== null && code_point !== EOF_code_point) { if (code_point <= 0xFFFF) { if (code_point > 0) result += String.fromCharCode(code_point); } else { code_point -= 0x10000; result += String.fromCharCode(0xD800 + ((code_point >> 10) & 0x3ff)); result += String.fromCharCode(0xDC00 + (code_point & 0x3ff)); } } } return result; } private _parseBinaryTimeline(type: TimelineType, offset: number, timelineData: TimelineData | null = null): TimelineData { const timeline = timelineData !== null ? timelineData : BaseObject.borrowObject(TimelineData); timeline.type = type; timeline.offset = offset; this._timeline = timeline; const keyFrameCount = this._timelineArrayBuffer[timeline.offset + BinaryOffset.TimelineKeyFrameCount]; if (keyFrameCount === 1) { timeline.frameIndicesOffset = -1; } else { let frameIndicesOffset = 0; const totalFrameCount = this._animation.frameCount + 1; // One more frame than animation. const frameIndices = this._data.frameIndices; frameIndicesOffset = frameIndices.length; frameIndices.length += totalFrameCount; timeline.frameIndicesOffset = frameIndicesOffset; for ( let i = 0, iK = 0, frameStart = 0, frameCount = 0; i < totalFrameCount; ++i ) { if (frameStart + frameCount <= i && iK < keyFrameCount) { frameStart = this._frameArrayBuffer[this._animation.frameOffset + this._timelineArrayBuffer[timeline.offset + BinaryOffset.TimelineFrameOffset + iK]]; if (iK === keyFrameCount - 1) { frameCount = this._animation.frameCount - frameStart; } else { frameCount = this._frameArrayBuffer[this._animation.frameOffset + this._timelineArrayBuffer[timeline.offset + BinaryOffset.TimelineFrameOffset + iK + 1]] - frameStart; } iK++; } frameIndices[frameIndicesOffset + i] = iK - 1; } } this._timeline = null as any; // return timeline; } protected _parseAnimation(rawData: any): AnimationData { const animation = BaseObject.borrowObject(AnimationData); animation.blendType = DataParser._getAnimationBlendType(ObjectDataParser._getString(rawData, DataParser.BLEND_TYPE, "")); animation.frameCount = ObjectDataParser._getNumber(rawData, DataParser.DURATION, 0); animation.playTimes = ObjectDataParser._getNumber(rawData, DataParser.PLAY_TIMES, 1); animation.duration = animation.frameCount / this._armature.frameRate; // float animation.fadeInTime = ObjectDataParser._getNumber(rawData, DataParser.FADE_IN_TIME, 0.0); animation.scale = ObjectDataParser._getNumber(rawData, DataParser.SCALE, 1.0); animation.name = ObjectDataParser._getString(rawData, DataParser.NAME, DataParser.DEFAULT_NAME); if (animation.name.length === 0) { animation.name = DataParser.DEFAULT_NAME; } // Offsets. const offsets = rawData[DataParser.OFFSET] as Array<number>; animation.frameIntOffset = offsets[0]; animation.frameFloatOffset = offsets[1]; animation.frameOffset = offsets[2]; this._animation = animation; if (DataParser.ACTION in rawData) { animation.actionTimeline = this._parseBinaryTimeline(TimelineType.Action, rawData[DataParser.ACTION]); } if (DataParser.Z_ORDER in rawData) { animation.zOrderTimeline = this._parseBinaryTimeline(TimelineType.ZOrder, rawData[DataParser.Z_ORDER]); } if (DataParser.BONE in rawData) { const rawTimeliness = rawData[DataParser.BONE]; for (let k in rawTimeliness) { const rawTimelines = rawTimeliness[k] as Array<number>; const bone = this._armature.getBone(k); if (bone === null) { continue; } for (let i = 0, l = rawTimelines.length; i < l; i += 2) { const timelineType = rawTimelines[i]; const timelineOffset = rawTimelines[i + 1]; const timeline = this._parseBinaryTimeline(timelineType, timelineOffset); this._animation.addBoneTimeline(bone.name, timeline); } } } if (DataParser.SLOT in rawData) { const rawTimeliness = rawData[DataParser.SLOT]; for (let k in rawTimeliness) { const rawTimelines = rawTimeliness[k] as Array<number>; const slot = this._armature.getSlot(k); if (slot === null) { continue; } for (let i = 0, l = rawTimelines.length; i < l; i += 2) { const timelineType = rawTimelines[i]; const timelineOffset = rawTimelines[i + 1]; const timeline = this._parseBinaryTimeline(timelineType, timelineOffset); this._animation.addSlotTimeline(slot.name, timeline); } } } if (DataParser.CONSTRAINT in rawData) { const rawTimeliness = rawData[DataParser.CONSTRAINT]; for (let k in rawTimeliness) { const rawTimelines = rawTimeliness[k] as Array<number>; const constraint = this._armature.getConstraint(k); if (constraint === null) { continue; } for (let i = 0, l = rawTimelines.length; i < l; i += 2) { const timelineType = rawTimelines[i]; const timelineOffset = rawTimelines[i + 1]; const timeline = this._parseBinaryTimeline(timelineType, timelineOffset); this._animation.addConstraintTimeline(constraint.name, timeline); } } } if (DataParser.TIMELINE in rawData) { const rawTimelines = rawData[DataParser.TIMELINE] as Array<any>; for (const rawTimeline of rawTimelines) { const timelineOffset = ObjectDataParser._getNumber(rawTimeline, DataParser.OFFSET, 0); if (timelineOffset >= 0) { const timelineType = ObjectDataParser._getNumber(rawTimeline, DataParser.TYPE, TimelineType.Action); const timelineName = ObjectDataParser._getString(rawTimeline, DataParser.NAME, ""); let timeline: TimelineData | null = null; if (timelineType === TimelineType.AnimationProgress && animation.blendType !== AnimationBlendType.None) { timeline = BaseObject.borrowObject(AnimationTimelineData); const animaitonTimeline = timeline as AnimationTimelineData; animaitonTimeline.x = ObjectDataParser._getNumber(rawTimeline, DataParser.X, 0.0); animaitonTimeline.y = ObjectDataParser._getNumber(rawTimeline, DataParser.Y, 0.0); } timeline = this._parseBinaryTimeline(timelineType, timelineOffset, timeline); switch (timelineType) { case TimelineType.Action: // TODO break; case TimelineType.ZOrder: // TODO break; case TimelineType.BoneTranslate: case TimelineType.BoneRotate: case TimelineType.BoneScale: case TimelineType.Surface: case TimelineType.BoneAlpha: this._animation.addBoneTimeline(timelineName, timeline); break; case TimelineType.SlotDisplay: case TimelineType.SlotColor: case TimelineType.SlotDeform: case TimelineType.SlotZIndex: case TimelineType.SlotAlpha: this._animation.addSlotTimeline(timelineName, timeline); break; case TimelineType.IKConstraint: this._animation.addConstraintTimeline(timelineName, timeline); break; case TimelineType.AnimationProgress: case TimelineType.AnimationWeight: case TimelineType.AnimationParameter: this._animation.addAnimationTimeline(timelineName, timeline); break; } } } } this._animation = null as any; return animation; } protected _parseGeometry(rawData: any, geometry: GeometryData): void { geometry.offset = rawData[DataParser.OFFSET]; geometry.data = this._data; let weightOffset = this._intArrayBuffer[geometry.offset + BinaryOffset.GeometryWeightOffset]; if (weightOffset < -1) { // -1 is a special flag that there is no bones weight. weightOffset += 65536; // Fixed out of bounds bug. } if (weightOffset >= 0) { const weight = BaseObject.borrowObject(WeightData); const vertexCount = this._intArrayBuffer[geometry.offset + BinaryOffset.GeometryVertexCount]; const boneCount = this._intArrayBuffer[weightOffset + BinaryOffset.WeigthBoneCount]; weight.offset = weightOffset; for (let i = 0; i < boneCount; ++i) { const boneIndex = this._intArrayBuffer[weightOffset + BinaryOffset.WeigthBoneIndices + i]; weight.addBone(this._rawBones[boneIndex]); } let boneIndicesOffset = weightOffset + BinaryOffset.WeigthBoneIndices + boneCount; let weightCount = 0; for (let i = 0, l = vertexCount; i < l; ++i) { const vertexBoneCount = this._intArrayBuffer[boneIndicesOffset++]; weightCount += vertexBoneCount; boneIndicesOffset += vertexBoneCount; } weight.count = weightCount; geometry.weight = weight; } } protected _parseArray(rawData: any): void { const offsets = rawData[DataParser.OFFSET] as Array<number>; const l1 = offsets[1]; const l2 = offsets[3]; const l3 = offsets[5]; const l4 = offsets[7]; const l5 = offsets[9]; const l6 = offsets[11]; const l7 = offsets.length > 12 ? offsets[13] : 0; // Color. const intArray = new Int16Array(this._binary, this._binaryOffset + offsets[0], l1 / Int16Array.BYTES_PER_ELEMENT); const floatArray = new Float32Array(this._binary, this._binaryOffset + offsets[2], l2 / Float32Array.BYTES_PER_ELEMENT); const frameIntArray = new Int16Array(this._binary, this._binaryOffset + offsets[4], l3 / Int16Array.BYTES_PER_ELEMENT); const frameFloatArray = new Float32Array(this._binary, this._binaryOffset + offsets[6], l4 / Float32Array.BYTES_PER_ELEMENT); const frameArray = new Int16Array(this._binary, this._binaryOffset + offsets[8], l5 / Int16Array.BYTES_PER_ELEMENT); const timelineArray = new Uint16Array(this._binary, this._binaryOffset + offsets[10], l6 / Uint16Array.BYTES_PER_ELEMENT); const colorArray = l7 > 0 ? new Int16Array(this._binary, this._binaryOffset + offsets[12], l7 / Uint16Array.BYTES_PER_ELEMENT) : intArray; // Color. this._data.binary = this._binary; this._data.intArray = this._intArrayBuffer = intArray; this._data.floatArray = floatArray; this._data.frameIntArray = frameIntArray; this._data.frameFloatArray = frameFloatArray; this._data.frameArray = this._frameArrayBuffer = frameArray; this._data.timelineArray = this._timelineArrayBuffer = timelineArray; this._data.colorArray = colorArray; } public parseDragonBonesData(rawData: any, scale: number = 1): DragonBonesData | null { console.assert(rawData !== null && rawData !== undefined && rawData instanceof ArrayBuffer, "Data error."); const tag = new Uint8Array(rawData, 0, 8); if ( tag[0] !== "D".charCodeAt(0) || tag[1] !== "B".charCodeAt(0) || tag[2] !== "D".charCodeAt(0) || tag[3] !== "T".charCodeAt(0) ) { console.assert(false, "Nonsupport data."); return null; } const headerLength = new Uint32Array(rawData, 8, 1)[0]; const headerBytes = new Uint8Array(rawData, 8 + 4, headerLength); const headerString = this._decodeUTF8(headerBytes); const header = JSON.parse(headerString); // this._binaryOffset = 8 + 4 + headerLength; this._binary = rawData; return super.parseDragonBonesData(header, scale); } private static _binaryDataParserInstance: BinaryDataParser | null = null; /** * - Deprecated, please refer to {@link dragonBones.BaseFactory#parseDragonBonesData()}. * @deprecated * @language en_US */ /** * - 已废弃,请参考 {@link dragonBones.BaseFactory#parseDragonBonesData()}。 * @deprecated * @language zh_CN */ public static getInstance(): BinaryDataParser { if (BinaryDataParser._binaryDataParserInstance === null) { BinaryDataParser._binaryDataParserInstance = new BinaryDataParser(); } return BinaryDataParser._binaryDataParserInstance; } } }
the_stack
import hl=require("../../parser/highLevelAST"); import core=require("../../parser/wrapped-ast/parserCoreApi"); export interface Annotable extends core.BasicNode{ /** * Most of RAML model elements may have attached annotations decribing additional meta data about this element **/ annotations( ):AnnotationRef[] } export interface ValueType extends core.AttributeNode{ /** * @return JS representation of the node value **/ value( ):any } export interface StringType extends ValueType{ /** * @return String representation of the node value **/ value( ):string } /** * This type currently serves both for absolute and relative urls **/ export interface UriTemplate extends StringType{} /** * This type describes relative uri templates **/ export interface RelativeUriString extends UriTemplate{} /** * This type describes absolute uri templates **/ export interface FullUriTemplateString extends UriTemplate{} export interface StatusCodeString extends StringType{} /** * This type describes fixed uris **/ export interface FixedUriString extends StringType{} export interface ContentType extends StringType{} /** * [GitHub Flavored Markdown](https://help.github.com/articles/github-flavored-markdown/) **/ export interface MarkdownString extends StringType{} /** * Schema at this moment only two subtypes are supported (json schema and xsd) **/ export interface SchemaString extends StringType{} /** * This sub type of the string represents mime types **/ export interface MimeType extends StringType{} export interface AnyType extends ValueType{} export interface NumberType extends ValueType{ /** * @return Number representation of the node value **/ value( ):number } export interface IntegerType extends ValueType{} export interface NullType extends ValueType{} export interface TimeOnlyType extends ValueType{} export interface DateOnlyType extends ValueType{} export interface DateTimeOnlyType extends ValueType{} export interface DateTimeType extends ValueType{} export interface FileType extends ValueType{} export interface BooleanType extends ValueType{ /** * @return Boolean representation of the node value **/ value( ):boolean } /** * Elements to which this Annotation can be applied (enum) **/ export interface AnnotationTarget extends ValueType{} export interface Reference extends core.AttributeNode{ /** * Returns a structured object if the reference point to one. **/ structuredValue( ):TypeInstance /** * Returns name of referenced object **/ name( ):string /** * @return StructuredValue object representing the node value **/ value( ):hl.IStructuredValue } export interface TypeInstance{ /** * Array of instance properties **/ properties( ):TypeInstanceProperty[] /** * Whether the type is scalar **/ isScalar( ):boolean /** * For instances of scalar types returns scalar value **/ value( ):any /** * Indicates whether the instance is array **/ isArray( ):boolean /** * Returns components of array instances **/ items( ):TypeInstance[] } export interface TypeInstanceProperty{ /** * Property name **/ name( ):string /** * Property value **/ value( ):TypeInstance /** * Array of values if property value is array **/ values( ):TypeInstance[] /** * Whether property has array as value **/ isArray( ):boolean } export interface TraitRef extends Reference{ /** * Returns referenced trait **/ trait( ):Trait } export interface Operation extends Annotable{ /** * An APIs resources MAY be filtered (to return a subset of results) or altered (such as transforming a response body from JSON to XML format) by the use of query strings. If the resource or its method supports a query string, the query string MUST be defined by the queryParameters property **/ queryParameters( ):TypeDeclaration[] /** * Headers that allowed at this position **/ headers( ):TypeDeclaration[] /** * Specifies the query string needed by this method. Mutually exclusive with queryParameters. **/ queryString( ):TypeDeclaration /** * Information about the expected responses to a request **/ responses( ):Response[] } export interface TypeDeclaration extends Annotable{ /** * Type name for top level types. For properties and parameters -- property o parameter name, respectively. For bodies -- media type. **/ name( ):string /** * The displayName attribute specifies the type display name. It is a friendly name used only for display or documentation purposes. If displayName is not specified, it defaults to the element's key (the name of the property itself). **/ displayName( ):string /** * When extending from a type you can define new facets (which can then be set to concrete values by subtypes). **/ facets( ):TypeDeclaration[] /** * Location of the parameter (can not be edited by user) **/ location( ):ModelLocation /** * Kind of location **/ locationKind( ):LocationKind /** * Provides default value for a property **/ "default"( ):any /** * An example of this type instance represented as string or yaml map/sequence. This can be used, e.g., by documentation generators to generate sample values for an object of this type. Cannot be present if the examples property is present. **/ example( ):ExampleSpec /** * An example of this type instance represented as string. This can be used, e.g., by documentation generators to generate sample values for an object of this type. Cannot be present if the example property is present. **/ examples( ):ExampleSpec[] /** * For property or parameter states if it is required. **/ required( ):boolean /** * A longer, human-friendly description of the type **/ description( ):MarkdownString xml( ):XMLFacetInfo /** * Restrictions on where annotations of this type can be applied. If this property is specified, annotations of this type may only be applied on a property corresponding to one of the target names specified as the value of this property. **/ allowedTargets( ):AnnotationTarget[] /** * Whether the type represents annotation **/ isAnnotation( ):boolean /** * Most of RAML model elements may have attached annotations decribing additional meta data about this element **/ annotations( ):AnnotationRef[] /** * Returns facets fixed by the type. Value is an object with properties named after facets fixed. Value of each property is a value of the corresponding facet. **/ fixedFacets( ):TypeInstance /** * Inlined supertype definition. **/ structuredType( ):TypeInstance /** * For types defined in traits or resource types returns object representation of parametrized properties **/ parametrizedProperties( ):TypeInstance /** * Runtime representation of type represented by this AST node **/ runtimeType( ):hl.ITypeDefinition /** * validate an instance against type **/ validateInstance( value:any ):string[] /** * validate an instance against type **/ validateInstanceWithDetailedStatuses( value:any ):any /** * A base type which the current type extends, or more generally a type expression. **/ "type"( ):string[] /** * A base type which the current type extends, or more generally a type expression. **/ schema( ):string[] /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):TypeDeclarationScalarsAnnotations } export interface ModelLocation extends core.AbstractWrapperNode{} export interface LocationKind extends core.AbstractWrapperNode{} export interface ExampleSpec extends Annotable{ /** * String representation of example **/ value( ):any /** * By default, examples are validated against any type declaration. Set this to false to allow examples that need not validate. **/ strict( ):boolean /** * Example identifier, if specified **/ name( ):string /** * An alternate, human-friendly name for the example **/ displayName( ):string /** * A longer, human-friendly description of the example **/ description( ):MarkdownString /** * Most of RAML model elements may have attached annotations decribing additional meta data about this element **/ annotations( ):AnnotationRef[] /** * Returns object representation of example, if possible **/ structuredValue( ):TypeInstance /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):ExampleSpecScalarsAnnotations } export interface UsesDeclaration extends Annotable{ /** * Name prefix (without dot) used to refer imported declarations **/ key( ):string /** * Content of the schema **/ value( ):string /** * Returns the root node of the AST, uses statement refers. **/ ast( ):Library /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):UsesDeclarationScalarsAnnotations } /** * UsesDeclaration scalar properties annotations accessor **/ export interface UsesDeclarationScalarsAnnotations{ /** * UsesDeclaration.value annotations **/ value( ):AnnotationRef[] } /** * ExampleSpec scalar properties annotations accessor **/ export interface ExampleSpecScalarsAnnotations{ /** * ExampleSpec.strict annotations **/ strict( ):AnnotationRef[] /** * ExampleSpec.displayName annotations **/ displayName( ):AnnotationRef[] /** * ExampleSpec.description annotations **/ description( ):AnnotationRef[] } export interface XMLFacetInfo extends Annotable{ /** * If attribute is set to true, a type instance should be serialized as an XML attribute. It can only be true for scalar types. **/ attribute( ):boolean /** * If wrapped is set to true, a type instance should be wrapped in its own XML element. It can not be true for scalar types and it can not be true at the same moment when attribute is true. **/ wrapped( ):boolean /** * Allows to override the name of the XML element or XML attribute in it's XML representation. **/ name( ):string /** * Allows to configure the name of the XML namespace. **/ namespace( ):string /** * Allows to configure the prefix which will be used during serialization to XML. **/ prefix( ):string /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):XMLFacetInfoScalarsAnnotations } /** * XMLFacetInfo scalar properties annotations accessor **/ export interface XMLFacetInfoScalarsAnnotations{ /** * XMLFacetInfo.attribute annotations **/ attribute( ):AnnotationRef[] /** * XMLFacetInfo.wrapped annotations **/ wrapped( ):AnnotationRef[] /** * XMLFacetInfo.name annotations **/ name( ):AnnotationRef[] /** * XMLFacetInfo.namespace annotations **/ namespace( ):AnnotationRef[] /** * XMLFacetInfo.prefix annotations **/ prefix( ):AnnotationRef[] } export interface ArrayTypeDeclaration extends TypeDeclaration{ /** * Should items in array be unique **/ uniqueItems( ):boolean /** * Minimum amount of items in array **/ minItems( ):number /** * Maximum amount of items in array **/ maxItems( ):number /** * Inlined component type definition **/ structuredItems( ):TypeInstance /** * Anonymous type declaration defined by "items" keyword. * If no "items" is defined explicitly, this one is null. **/ items( ):string[] /** * Returns anonymous type defined by "items" keyword, or a component type if declaration can be found. * Does not resolve type expressions. Only returns component type declaration if it is actually defined * somewhere in AST. **/ findComponentTypeDeclaration( ):TypeDeclaration /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):ArrayTypeDeclarationScalarsAnnotations } /** * TypeDeclaration scalar properties annotations accessor **/ export interface TypeDeclarationScalarsAnnotations{ /** * TypeDeclaration.displayName annotations **/ displayName( ):AnnotationRef[] /** * TypeDeclaration.schema annotations **/ schema( ):AnnotationRef[][] /** * TypeDeclaration.type annotations **/ "type"( ):AnnotationRef[][] /** * TypeDeclaration.location annotations **/ location( ):AnnotationRef[] /** * TypeDeclaration.locationKind annotations **/ locationKind( ):AnnotationRef[] /** * TypeDeclaration.default annotations **/ "default"( ):AnnotationRef[] /** * TypeDeclaration.required annotations **/ required( ):AnnotationRef[] /** * TypeDeclaration.description annotations **/ description( ):AnnotationRef[] /** * TypeDeclaration.allowedTargets annotations **/ allowedTargets( ):AnnotationRef[][] /** * TypeDeclaration.isAnnotation annotations **/ isAnnotation( ):AnnotationRef[] } /** * ArrayTypeDeclaration scalar properties annotations accessor **/ export interface ArrayTypeDeclarationScalarsAnnotations extends TypeDeclarationScalarsAnnotations{ /** * ArrayTypeDeclaration.uniqueItems annotations **/ uniqueItems( ):AnnotationRef[] /** * ArrayTypeDeclaration.items annotations **/ items( ):AnnotationRef[][] /** * ArrayTypeDeclaration.minItems annotations **/ minItems( ):AnnotationRef[] /** * ArrayTypeDeclaration.maxItems annotations **/ maxItems( ):AnnotationRef[] } export interface UnionTypeDeclaration extends TypeDeclaration{} export interface ObjectTypeDeclaration extends TypeDeclaration{ /** * The properties that instances of this type may or must have. **/ properties( ):TypeDeclaration[] /** * The minimum number of properties allowed for instances of this type. **/ minProperties( ):number /** * The maximum number of properties allowed for instances of this type. **/ maxProperties( ):number /** * A Boolean that indicates if an object instance has additional properties. **/ additionalProperties( ):boolean /** * Type property name to be used as discriminator, or boolean **/ discriminator( ):string /** * The value of discriminator for the type. **/ discriminatorValue( ):string enum( ):any[] /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):ObjectTypeDeclarationScalarsAnnotations } /** * ObjectTypeDeclaration scalar properties annotations accessor **/ export interface ObjectTypeDeclarationScalarsAnnotations extends TypeDeclarationScalarsAnnotations{ /** * ObjectTypeDeclaration.minProperties annotations **/ minProperties( ):AnnotationRef[] /** * ObjectTypeDeclaration.maxProperties annotations **/ maxProperties( ):AnnotationRef[] /** * ObjectTypeDeclaration.additionalProperties annotations **/ additionalProperties( ):AnnotationRef[] /** * ObjectTypeDeclaration.discriminator annotations **/ discriminator( ):AnnotationRef[] /** * ObjectTypeDeclaration.discriminatorValue annotations **/ discriminatorValue( ):AnnotationRef[] /** * ObjectTypeDeclaration.enum annotations **/ enum( ):AnnotationRef[][] } /** * Value must be a string **/ export interface StringTypeDeclaration extends TypeDeclaration{ /** * Regular expression that this string should path **/ pattern( ):string /** * Minimum length of the string **/ minLength( ):number /** * Maximum length of the string **/ maxLength( ):number /** * (Optional, applicable only for parameters of type string) The enum attribute provides an enumeration of the parameter's valid values. This MUST be an array. If the enum attribute is defined, API clients and servers MUST verify that a parameter's value matches a value in the enum array. If there is no matching value, the clients and servers MUST treat this as an error. **/ enum( ):string[] /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):StringTypeDeclarationScalarsAnnotations } /** * StringTypeDeclaration scalar properties annotations accessor **/ export interface StringTypeDeclarationScalarsAnnotations extends TypeDeclarationScalarsAnnotations{ /** * StringTypeDeclaration.pattern annotations **/ pattern( ):AnnotationRef[] /** * StringTypeDeclaration.minLength annotations **/ minLength( ):AnnotationRef[] /** * StringTypeDeclaration.maxLength annotations **/ maxLength( ):AnnotationRef[] /** * StringTypeDeclaration.enum annotations **/ enum( ):AnnotationRef[][] } /** * Value must be a boolean **/ export interface BooleanTypeDeclaration extends TypeDeclaration{ enum( ):boolean[] /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):BooleanTypeDeclarationScalarsAnnotations } /** * BooleanTypeDeclaration scalar properties annotations accessor **/ export interface BooleanTypeDeclarationScalarsAnnotations extends TypeDeclarationScalarsAnnotations{ /** * BooleanTypeDeclaration.enum annotations **/ enum( ):AnnotationRef[][] } /** * Value MUST be a number. Indicate floating point numbers as defined by YAML. **/ export interface NumberTypeDeclaration extends TypeDeclaration{ /** * (Optional, applicable only for parameters of type number or integer) The minimum attribute specifies the parameter's minimum value. **/ minimum( ):number /** * (Optional, applicable only for parameters of type number or integer) The maximum attribute specifies the parameter's maximum value. **/ maximum( ):number /** * (Optional, applicable only for parameters of type string) The enum attribute provides an enumeration of the parameter's valid values. This MUST be an array. If the enum attribute is defined, API clients and servers MUST verify that a parameter's value matches a value in the enum array. If there is no matching value, the clients and servers MUST treat this as an error. **/ enum( ):number[] /** * Value format **/ format( ):string /** * A numeric instance is valid against "multipleOf" if the result of the division of the instance by this keyword's value is an integer. **/ multipleOf( ):number /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):NumberTypeDeclarationScalarsAnnotations } /** * Value MUST be a integer. **/ export interface IntegerTypeDeclaration extends NumberTypeDeclaration{ /** * Value format **/ format( ):string /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):IntegerTypeDeclarationScalarsAnnotations } /** * NumberTypeDeclaration scalar properties annotations accessor **/ export interface NumberTypeDeclarationScalarsAnnotations extends TypeDeclarationScalarsAnnotations{ /** * NumberTypeDeclaration.minimum annotations **/ minimum( ):AnnotationRef[] /** * NumberTypeDeclaration.maximum annotations **/ maximum( ):AnnotationRef[] /** * NumberTypeDeclaration.enum annotations **/ enum( ):AnnotationRef[][] /** * NumberTypeDeclaration.format annotations **/ format( ):AnnotationRef[] /** * NumberTypeDeclaration.multipleOf annotations **/ multipleOf( ):AnnotationRef[] } /** * IntegerTypeDeclaration scalar properties annotations accessor **/ export interface IntegerTypeDeclarationScalarsAnnotations extends NumberTypeDeclarationScalarsAnnotations{ /** * IntegerTypeDeclaration.format annotations **/ format( ):AnnotationRef[] } /** * the "full-date" notation of RFC3339, namely yyyy-mm-dd (no implications about time or timezone-offset) **/ export interface DateOnlyTypeDeclaration extends TypeDeclaration{} /** * the "partial-time" notation of RFC3339, namely hh:mm:ss[.ff...] (no implications about date or timezone-offset) **/ export interface TimeOnlyTypeDeclaration extends TypeDeclaration{} /** * combined date-only and time-only with a separator of "T", namely yyyy-mm-ddThh:mm:ss[.ff...] (no implications about timezone-offset) **/ export interface DateTimeOnlyTypeDeclaration extends TypeDeclaration{} /** * a timestamp, either in the "date-time" notation of RFC3339, if format is omitted or is set to rfc3339, or in the format defined in RFC2616, if format is set to rfc2616. **/ export interface DateTimeTypeDeclaration extends TypeDeclaration{ /** * Format used for this date time rfc3339 or rfc2616 **/ format( ):string /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):DateTimeTypeDeclarationScalarsAnnotations } /** * DateTimeTypeDeclaration scalar properties annotations accessor **/ export interface DateTimeTypeDeclarationScalarsAnnotations extends TypeDeclarationScalarsAnnotations{ /** * DateTimeTypeDeclaration.format annotations **/ format( ):AnnotationRef[] } /** * (Applicable only to Form properties) Value is a file. Client generators SHOULD use this type to handle file uploads correctly. **/ export interface FileTypeDeclaration extends TypeDeclaration{ /** * A list of valid content-type strings for the file. The file type * /* should be a valid value. **/ fileTypes( ):ContentType[] /** * The minLength attribute specifies the parameter value's minimum number of bytes. **/ minLength( ):number /** * The maxLength attribute specifies the parameter value's maximum number of bytes. **/ maxLength( ):number /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):FileTypeDeclarationScalarsAnnotations } /** * FileTypeDeclaration scalar properties annotations accessor **/ export interface FileTypeDeclarationScalarsAnnotations extends TypeDeclarationScalarsAnnotations{ /** * FileTypeDeclaration.fileTypes annotations **/ fileTypes( ):AnnotationRef[][] /** * FileTypeDeclaration.minLength annotations **/ minLength( ):AnnotationRef[] /** * FileTypeDeclaration.maxLength annotations **/ maxLength( ):AnnotationRef[] } export interface Response extends Annotable{ /** * Responses MUST be a map of one or more HTTP status codes, where each status code itself is a map that describes that status code. **/ code( ):StatusCodeString /** * Detailed information about any response headers returned by this method **/ headers( ):TypeDeclaration[] /** * The body of the response: a body declaration **/ body( ):TypeDeclaration[] /** * A longer, human-friendly description of the response **/ description( ):MarkdownString /** * Most of RAML model elements may have attached annotations decribing additional meta data about this element **/ annotations( ):AnnotationRef[] /** * For responses defined in traits or resource types returns object representation of parametrized properties **/ parametrizedProperties( ):TypeInstance /** * true for codes < 400 and false otherwise **/ isOkRange( ):boolean /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):ResponseScalarsAnnotations } /** * Response scalar properties annotations accessor **/ export interface ResponseScalarsAnnotations{ /** * Response.description annotations **/ description( ):AnnotationRef[] } export interface SecuritySchemePart extends Operation{ /** * Annotations to be applied to this security scheme part. Annotations are any property whose key begins with "(" and ends with ")" and whose name (the part between the beginning and ending parentheses) is a declared annotation name. **/ annotations( ):AnnotationRef[] } export interface MethodBase extends Operation{ /** * Some method verbs expect the resource to be sent as a request body. For example, to create a resource, the request must include the details of the resource to create. Resources CAN have alternate representations. For example, an API might support both JSON and XML representations. A method's body is defined in the body property as a hashmap, in which the key MUST be a valid media type. **/ body( ):TypeDeclaration[] /** * A method can override the protocols specified in the resource or at the API root, by employing this property. **/ protocols( ):string[] /** * Instantiation of applyed traits **/ is( ):TraitRef[] /** * securityScheme may also be applied to a resource by using the securedBy key, which is equivalent to applying the securityScheme to all methods that may be declared, explicitly or implicitly, by defining the resourceTypes or traits property for that resource. To indicate that the method may be called without applying any securityScheme, the method may be annotated with the null securityScheme. **/ securedBy( ):SecuritySchemeRef[] description( ):MarkdownString displayName( ):string /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):MethodBaseScalarsAnnotations } export interface SecuritySchemeRef extends Reference{ /** * Returns the name of security scheme, this reference refers to. **/ securitySchemeName( ):string /** * Returns AST node of security scheme, this reference refers to, or null. **/ securityScheme( ):AbstractSecurityScheme } /** * Declares globally referable security scheme definition **/ export interface AbstractSecurityScheme extends Annotable{ /** * Name of the security scheme **/ name( ):string /** * The securitySchemes property MUST be used to specify an API's security mechanisms, including the required settings and the authentication methods that the API supports. one authentication method is allowed if the API supports them. **/ "type"( ):string /** * The description MAY be used to describe a securityScheme. **/ description( ):MarkdownString /** * A description of the request components related to Security that are determined by the scheme: the headers, query parameters or responses. As a best practice, even for standard security schemes, API designers SHOULD describe these properties of security schemes. Including the security scheme description completes an API documentation. **/ describedBy( ):SecuritySchemePart /** * The displayName attribute specifies the security scheme display name. It is a friendly name used only for display or documentation purposes. If displayName is not specified, it defaults to the element's key (the name of the property itself). **/ displayName( ):string /** * The settings attribute MAY be used to provide security scheme-specific information. The required attributes vary depending on the type of security scheme is being declared. It describes the minimum set of properties which any processing application MUST provide and validate if it chooses to implement the security scheme. Processing applications MAY choose to recognize other properties for things such as token lifetime, preferred cryptographic algorithms, and more. **/ settings( ):SecuritySchemeSettings /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):AbstractSecuritySchemeScalarsAnnotations } export interface SecuritySchemeSettings extends Annotable{} export interface OAuth1SecuritySchemeSettings extends SecuritySchemeSettings{ /** * The URI of the Temporary Credential Request endpoint as defined in RFC5849 Section 2.1 **/ requestTokenUri( ):FixedUriString /** * The URI of the Resource Owner Authorization endpoint as defined in RFC5849 Section 2.2 **/ authorizationUri( ):FixedUriString /** * The URI of the Token Request endpoint as defined in RFC5849 Section 2.3 **/ tokenCredentialsUri( ):FixedUriString /** * List of the signature methods used by the server. Available methods: HMAC-SHA1, RSA-SHA1, PLAINTEXT **/ signatures( ):string[] /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):OAuth1SecuritySchemeSettingsScalarsAnnotations } /** * OAuth1SecuritySchemeSettings scalar properties annotations accessor **/ export interface OAuth1SecuritySchemeSettingsScalarsAnnotations{ /** * OAuth1SecuritySchemeSettings.requestTokenUri annotations **/ requestTokenUri( ):AnnotationRef[] /** * OAuth1SecuritySchemeSettings.authorizationUri annotations **/ authorizationUri( ):AnnotationRef[] /** * OAuth1SecuritySchemeSettings.tokenCredentialsUri annotations **/ tokenCredentialsUri( ):AnnotationRef[] /** * OAuth1SecuritySchemeSettings.signatures annotations **/ signatures( ):AnnotationRef[][] } export interface OAuth2SecuritySchemeSettings extends SecuritySchemeSettings{ /** * The URI of the Token Endpoint as defined in RFC6749 Section 3.2. Not required forby implicit grant type. **/ accessTokenUri( ):FixedUriString /** * The URI of the Authorization Endpoint as defined in RFC6749 Section 3.1. Required forby authorization_code and implicit grant types. **/ authorizationUri( ):FixedUriString /** * A list of the Authorization grants supported by the API as defined in RFC6749 Sections 4.1, 4.2, 4.3 and 4.4, can be any of: authorization_code, password, client_credentials, implicit, or any absolute url. **/ authorizationGrants( ):string[] /** * A list of scopes supported by the security scheme as defined in RFC6749 Section 3.3 **/ scopes( ):string[] /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):OAuth2SecuritySchemeSettingsScalarsAnnotations } /** * OAuth2SecuritySchemeSettings scalar properties annotations accessor **/ export interface OAuth2SecuritySchemeSettingsScalarsAnnotations{ /** * OAuth2SecuritySchemeSettings.accessTokenUri annotations **/ accessTokenUri( ):AnnotationRef[] /** * OAuth2SecuritySchemeSettings.authorizationUri annotations **/ authorizationUri( ):AnnotationRef[] /** * OAuth2SecuritySchemeSettings.authorizationGrants annotations **/ authorizationGrants( ):AnnotationRef[][] /** * OAuth2SecuritySchemeSettings.scopes annotations **/ scopes( ):AnnotationRef[][] } /** * Declares globally referable security scheme definition **/ export interface OAuth2SecurityScheme extends AbstractSecurityScheme{ settings( ):OAuth2SecuritySchemeSettings } /** * Declares globally referable security scheme definition **/ export interface OAuth1SecurityScheme extends AbstractSecurityScheme{ settings( ):OAuth1SecuritySchemeSettings } /** * Declares globally referable security scheme definition **/ export interface PassThroughSecurityScheme extends AbstractSecurityScheme{ settings( ):SecuritySchemeSettings } /** * Declares globally referable security scheme definition **/ export interface BasicSecurityScheme extends AbstractSecurityScheme{} /** * Declares globally referable security scheme definition **/ export interface DigestSecurityScheme extends AbstractSecurityScheme{} /** * Declares globally referable security scheme definition **/ export interface CustomSecurityScheme extends AbstractSecurityScheme{} /** * AbstractSecurityScheme scalar properties annotations accessor **/ export interface AbstractSecuritySchemeScalarsAnnotations{ /** * AbstractSecurityScheme.type annotations **/ "type"( ):AnnotationRef[] /** * AbstractSecurityScheme.description annotations **/ description( ):AnnotationRef[] /** * AbstractSecurityScheme.displayName annotations **/ displayName( ):AnnotationRef[] } export interface Method extends MethodBase{ /** * Method that can be called **/ method( ):string /** * The displayName attribute specifies the method display name. It is a friendly name used only for display or documentation purposes. If displayName is not specified, it defaults to the element's key (the name of the property itself). **/ displayName( ):string /** * For types defined in resource types returns object representation of parametrized properties **/ parametrizedProperties( ):TypeInstance /** * For methods of Resources returns parent resource. For methods of ResourceTypes returns null. **/ parentResource( ):Resource /** * Api owning the resource as a sibling **/ ownerApi( ):Api /** * For methods of Resources: `{parent Resource relative path} {methodName}`. * For methods of ResourceTypes: `{parent ResourceType name} {methodName}`. * For other methods throws Exception. **/ methodId( ):string /** * Returns security schemes, resource or method is secured with. If no security schemes are set at resource or method level, * returns schemes defined with `securedBy` at API level. * @deprecated **/ allSecuredBy( ):SecuritySchemeRef[] /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):MethodScalarsAnnotations } /** * MethodBase scalar properties annotations accessor **/ export interface MethodBaseScalarsAnnotations{ /** * MethodBase.protocols annotations **/ protocols( ):AnnotationRef[][] /** * MethodBase.is annotations **/ is( ):AnnotationRef[][] /** * MethodBase.securedBy annotations **/ securedBy( ):AnnotationRef[][] /** * MethodBase.description annotations **/ description( ):AnnotationRef[] /** * MethodBase.displayName annotations **/ displayName( ):AnnotationRef[] } /** * Method scalar properties annotations accessor **/ export interface MethodScalarsAnnotations extends MethodBaseScalarsAnnotations{ /** * Method.displayName annotations **/ displayName( ):AnnotationRef[] } export interface Trait extends MethodBase{ /** * Name of the trait **/ name( ):string /** * Instructions on how and when the trait should be used. **/ usage( ):string /** * The displayName attribute specifies the trait display name. It is a friendly name used only for display or documentation purposes. If displayName is not specified, it defaults to the element's key (the name of the property itself). **/ displayName( ):string /** * Returns object representation of parametrized properties of the trait **/ parametrizedProperties( ):TypeInstance /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):TraitScalarsAnnotations } /** * Trait scalar properties annotations accessor **/ export interface TraitScalarsAnnotations extends MethodBaseScalarsAnnotations{ /** * Trait.usage annotations **/ usage( ):AnnotationRef[] /** * Trait.displayName annotations **/ displayName( ):AnnotationRef[] } export interface ResourceTypeRef extends Reference{ /** * Returns referenced resource type **/ resourceType( ):ResourceType } export interface ResourceBase extends Annotable{ /** * Methods that are part of this resource type definition **/ methods( ):Method[] /** * A list of the traits to apply to all methods declared (implicitly or explicitly) for this resource. Individual methods may override this declaration **/ is( ):TraitRef[] /** * The resource type which this resource inherits. **/ "type"( ):ResourceTypeRef description( ):MarkdownString /** * The security schemes that apply to all methods declared (implicitly or explicitly) for this resource. **/ securedBy( ):SecuritySchemeRef[] /** * Retrieve an ordered list of all uri parameters including those which are not described in the `uriParameters` node. * Consider a fragment of RAML specification: * ```yaml * /resource/{objectId}/{propertyId}: * uriParameters: * objectId: * ``` * Here `propertyId` uri parameter is not described in the `uriParameters` node, * but it is among Resource.uriParameters(). **/ uriParameters( ):TypeDeclaration[] /** * Retrieve an ordered list of all uri parameters including those which are not described in the `uriParameters` node. * Consider a fragment of RAML specification: * ```yaml * /resource/{objectId}/{propertyId}: * uriParameters: * objectId: * ``` * Here `propertyId` uri parameter is not described in the `uriParameters` node, * but it is among Resource.allUriParameters(). * @deprecated **/ allUriParameters( ):TypeDeclaration[] /** * Returns security schemes, resource or method is secured with. If no security schemes are set at resource or method level, * returns schemes defined with `securedBy` at API level. * @deprecated **/ allSecuredBy( ):SecuritySchemeRef[] /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):ResourceBaseScalarsAnnotations } export interface Resource extends ResourceBase{ /** * Relative URL of this resource from the parent resource **/ relativeUri( ):RelativeUriString /** * The displayName attribute specifies the resource display name. It is a friendly name used only for display or documentation purposes. If displayName is not specified, it defaults to the element's key (the name of the property itself). **/ displayName( ):string /** * A nested resource is identified as any property whose name begins with a slash ("/") and is therefore treated as a relative URI. **/ resources( ):Resource[] /** * A longer, human-friendly description of the resource. **/ description( ):MarkdownString /** * Most of RAML model elements may have attached annotations decribing additional meta data about this element **/ annotations( ):AnnotationRef[] /** * Path relative to API root **/ completeRelativeUri( ):string /** * baseUri of owning Api concatenated with completeRelativeUri **/ absoluteUri( ):string /** * Parent resource for non top level resources **/ parentResource( ):Resource /** * Get child resource by its relative path **/ childResource( relPath:string ):Resource /** * Get child method by its name **/ childMethod( method:string ):Method[] /** * Api owning the resource as a sibling **/ ownerApi( ):Api /** * Retrieve an ordered list of all absolute uri parameters. Returns a union of `Api.baseUriParameters()` * for `Api` owning the `Resource` and `Resource.uriParameters()`. **/ absoluteUriParameters( ):TypeDeclaration[] /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):ResourceScalarsAnnotations } /** * ResourceBase scalar properties annotations accessor **/ export interface ResourceBaseScalarsAnnotations{ /** * ResourceBase.is annotations **/ is( ):AnnotationRef[][] /** * ResourceBase.type annotations **/ "type"( ):AnnotationRef[] /** * ResourceBase.description annotations **/ description( ):AnnotationRef[] /** * ResourceBase.securedBy annotations **/ securedBy( ):AnnotationRef[][] } /** * Resource scalar properties annotations accessor **/ export interface ResourceScalarsAnnotations extends ResourceBaseScalarsAnnotations{ /** * Resource.displayName annotations **/ displayName( ):AnnotationRef[] /** * Resource.description annotations **/ description( ):AnnotationRef[] } export interface ResourceType extends ResourceBase{ /** * The displayName attribute specifies the resource type display name. It is a friendly name used only for display or documentation purposes. If displayName is not specified, it defaults to the element's key (the name of the property itself). **/ displayName( ):string /** * Name of the resource type **/ name( ):string /** * Instructions on how and when the resource type should be used. **/ usage( ):string /** * Returns object representation of parametrized properties of the resource type **/ parametrizedProperties( ):TypeInstance /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):ResourceTypeScalarsAnnotations } /** * ResourceType scalar properties annotations accessor **/ export interface ResourceTypeScalarsAnnotations extends ResourceBaseScalarsAnnotations{ /** * ResourceType.displayName annotations **/ displayName( ):AnnotationRef[] /** * ResourceType.usage annotations **/ usage( ):AnnotationRef[] } /** * Annotations allow you to attach information to your API **/ export interface AnnotationRef extends Reference{ /** * Returns referenced annotation **/ annotation( ):TypeDeclaration } export interface DocumentationItem extends Annotable{ /** * Title of documentation section **/ title( ):string /** * Content of documentation section **/ content( ):MarkdownString /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):DocumentationItemScalarsAnnotations } /** * DocumentationItem scalar properties annotations accessor **/ export interface DocumentationItemScalarsAnnotations{ /** * DocumentationItem.title annotations **/ title( ):AnnotationRef[] /** * DocumentationItem.content annotations **/ content( ):AnnotationRef[] } export interface FragmentDeclaration extends Annotable{ uses( ):UsesDeclaration[] } export interface LibraryBase extends FragmentDeclaration{ /** * Alias for the equivalent "types" property, for compatibility with RAML 0.8. Deprecated - API definitions should use the "types" property, as the "schemas" alias for that property name may be removed in a future RAML version. The "types" property allows for XML and JSON schemas. **/ schemas( ):TypeDeclaration[] /** * Declarations of (data) types for use within this API **/ types( ):TypeDeclaration[] /** * Declarations of annotation types for use by annotations **/ annotationTypes( ):TypeDeclaration[] /** * Declarations of security schemes for use within this API. **/ securitySchemes( ):AbstractSecurityScheme[] /** * Retrieve all traits including those defined in libraries **/ traits( ):Trait[] /** * Retrieve all traits including those defined in libraries * @deprecated **/ allTraits( ):Trait[] /** * Retrieve all resource types including those defined in libraries **/ resourceTypes( ):ResourceType[] /** * Retrieve all resource types including those defined in libraries * @deprecated **/ allResourceTypes( ):ResourceType[] } export interface Library extends LibraryBase{ /** * contains description of why library exist **/ usage( ):string /** * Namespace which the library is imported under **/ name( ):string /** * Equivalent Library which contains all its dependencies **/ expand( ):Library /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):LibraryScalarsAnnotations } /** * Library scalar properties annotations accessor **/ export interface LibraryScalarsAnnotations{ /** * Library.usage annotations **/ usage( ):AnnotationRef[] } export interface Api extends LibraryBase{ /** * Short plain-text label for the API **/ title( ):string /** * A longer, human-friendly description of the API **/ description( ):MarkdownString /** * The version of the API, e.g. 'v1' **/ version( ):string /** * A URI that's to be used as the base of all the resources' URIs. Often used as the base of the URL of each resource, containing the location of the API. Can be a template URI. **/ baseUri( ):FullUriTemplateString /** * The protocols supported by the API **/ protocols( ):string[] /** * The default media type to use for request and response bodies (payloads), e.g. "application/json" **/ mediaType( ):MimeType[] /** * The security schemes that apply to every resource and method in the API **/ securedBy( ):SecuritySchemeRef[] /** * The resources of the API, identified as relative URIs that begin with a slash (/). Every property whose key begins with a slash (/), and is either at the root of the API definition or is the child property of a resource property, is a resource property, e.g.: /users, /{groupId}, etc **/ resources( ):Resource[] /** * Additional overall documentation for the API **/ documentation( ):DocumentationItem[] /** * Most of RAML model elements may have attached annotations decribing additional meta data about this element **/ annotations( ):AnnotationRef[] /** * Returns RAML version. "RAML10" string is returned for RAML 1.0. "RAML08" string is returned for RAML 0.8. **/ RAMLVersion( ):string /** * Equivalent API with traits and resource types expanded * @expLib whether to apply library expansion or not **/ expand( expLib?:boolean ):Api /** * Get child resource by its relative path **/ childResource( relPath:string ):Resource /** * Retrieve all resources of the Api **/ allResources( ):Resource[] /** * Retrieve an ordered list of all base uri parameters regardless of whether they are described in `baseUriParameters` or not * Consider a fragment of RAML specification: * ```yaml * version: v1 * baseUri: https://{organization}.example.com/{version}/{service} * baseUriParameters: * service: * ``` * Here `version` and `organization` are base uri parameters which are not described in the `baseUriParameters` node, * but they are among `Api.baseUriParameters()`. **/ baseUriParameters( ):TypeDeclaration[] /** * Retrieve an ordered list of all base uri parameters regardless of whether they are described in `baseUriParameters` or not * Consider a fragment of RAML specification: * ```yaml * version: v1 * baseUri: https://{organization}.example.com/{version}/{service} * baseUriParameters: * service: * ``` * Here `version` and `organization` are base uri parameters which are not described in the `baseUriParameters` node, * but they are among `Api.allBaseUriParameters()`. * @deprecated **/ allBaseUriParameters( ):TypeDeclaration[] /** * Protocols used by the API. Returns the `protocols` property value if it is specified. * Otherwise, returns protocol, specified in the base URI. * @deprecated **/ allProtocols( ):string[] /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):ApiScalarsAnnotations } export interface Overlay extends Api{ /** * contains description of why overlay exist **/ usage( ):string /** * Location of a valid RAML API definition (or overlay or extension), the overlay is applied to. **/ extends( ):string /** * Short plain-text label for the API **/ title( ):string /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):OverlayScalarsAnnotations } /** * Api scalar properties annotations accessor **/ export interface ApiScalarsAnnotations{ /** * Api.title annotations **/ title( ):AnnotationRef[] /** * Api.description annotations **/ description( ):AnnotationRef[] /** * Api.version annotations **/ version( ):AnnotationRef[] /** * Api.baseUri annotations **/ baseUri( ):AnnotationRef[] /** * Api.protocols annotations **/ protocols( ):AnnotationRef[][] /** * Api.mediaType annotations **/ mediaType( ):AnnotationRef[][] /** * Api.securedBy annotations **/ securedBy( ):AnnotationRef[][] } /** * Overlay scalar properties annotations accessor **/ export interface OverlayScalarsAnnotations extends ApiScalarsAnnotations{ /** * Overlay.usage annotations **/ usage( ):AnnotationRef[] /** * Overlay.extends annotations **/ extends( ):AnnotationRef[] /** * Overlay.title annotations **/ title( ):AnnotationRef[] } export interface Extension extends Api{ /** * contains description of why extension exist **/ usage( ):string /** * Location of a valid RAML API definition (or overlay or extension), the extension is applied to **/ extends( ):string /** * Short plain-text label for the API **/ title( ):string /** * Scalar properties annotations accessor **/ scalarsAnnotations( ):ExtensionScalarsAnnotations } /** * Extension scalar properties annotations accessor **/ export interface ExtensionScalarsAnnotations extends ApiScalarsAnnotations{ /** * Extension.usage annotations **/ usage( ):AnnotationRef[] /** * Extension.extends annotations **/ extends( ):AnnotationRef[] /** * Extension.title annotations **/ title( ):AnnotationRef[] } /** * Custom type guard for Api. Returns true if node is instance of Api. Returns false otherwise. * Also returns false for super interfaces of Api. */ export function isApi(node: core.AbstractWrapperNode) : node is Api { return node.kind() == "Api" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for LibraryBase. Returns true if node is instance of LibraryBase. Returns false otherwise. * Also returns false for super interfaces of LibraryBase. */ export function isLibraryBase(node: core.AbstractWrapperNode) : node is LibraryBase { return node.kind() == "LibraryBase" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for Annotable. Returns true if node is instance of Annotable. Returns false otherwise. * Also returns false for super interfaces of Annotable. */ export function isAnnotable(node: core.AbstractWrapperNode) : node is Annotable { return node.kind() == "Annotable" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for AnnotationRef. Returns true if node is instance of AnnotationRef. Returns false otherwise. * Also returns false for super interfaces of AnnotationRef. */ export function isAnnotationRef(node: core.AbstractWrapperNode) : node is AnnotationRef { return node.kind() == "AnnotationRef" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for Reference. Returns true if node is instance of Reference. Returns false otherwise. * Also returns false for super interfaces of Reference. */ export function isReference(node: core.AbstractWrapperNode) : node is Reference { return node.kind() == "Reference" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for ValueType. Returns true if node is instance of ValueType. Returns false otherwise. * Also returns false for super interfaces of ValueType. */ export function isValueType(node: core.AbstractWrapperNode) : node is ValueType { return node.kind() == "ValueType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for StringType. Returns true if node is instance of StringType. Returns false otherwise. * Also returns false for super interfaces of StringType. */ export function isStringType(node: core.AbstractWrapperNode) : node is StringType { return node.kind() == "StringType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for UriTemplate. Returns true if node is instance of UriTemplate. Returns false otherwise. * Also returns false for super interfaces of UriTemplate. */ export function isUriTemplate(node: core.AbstractWrapperNode) : node is UriTemplate { return node.kind() == "UriTemplate" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for RelativeUriString. Returns true if node is instance of RelativeUriString. Returns false otherwise. * Also returns false for super interfaces of RelativeUriString. */ export function isRelativeUriString(node: core.AbstractWrapperNode) : node is RelativeUriString { return node.kind() == "RelativeUriString" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for FullUriTemplateString. Returns true if node is instance of FullUriTemplateString. Returns false otherwise. * Also returns false for super interfaces of FullUriTemplateString. */ export function isFullUriTemplateString(node: core.AbstractWrapperNode) : node is FullUriTemplateString { return node.kind() == "FullUriTemplateString" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for StatusCodeString. Returns true if node is instance of StatusCodeString. Returns false otherwise. * Also returns false for super interfaces of StatusCodeString. */ export function isStatusCodeString(node: core.AbstractWrapperNode) : node is StatusCodeString { return node.kind() == "StatusCodeString" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for FixedUriString. Returns true if node is instance of FixedUriString. Returns false otherwise. * Also returns false for super interfaces of FixedUriString. */ export function isFixedUriString(node: core.AbstractWrapperNode) : node is FixedUriString { return node.kind() == "FixedUriString" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for ContentType. Returns true if node is instance of ContentType. Returns false otherwise. * Also returns false for super interfaces of ContentType. */ export function isContentType(node: core.AbstractWrapperNode) : node is ContentType { return node.kind() == "ContentType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for MarkdownString. Returns true if node is instance of MarkdownString. Returns false otherwise. * Also returns false for super interfaces of MarkdownString. */ export function isMarkdownString(node: core.AbstractWrapperNode) : node is MarkdownString { return node.kind() == "MarkdownString" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for SchemaString. Returns true if node is instance of SchemaString. Returns false otherwise. * Also returns false for super interfaces of SchemaString. */ export function isSchemaString(node: core.AbstractWrapperNode) : node is SchemaString { return node.kind() == "SchemaString" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for MimeType. Returns true if node is instance of MimeType. Returns false otherwise. * Also returns false for super interfaces of MimeType. */ export function isMimeType(node: core.AbstractWrapperNode) : node is MimeType { return node.kind() == "MimeType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for AnyType. Returns true if node is instance of AnyType. Returns false otherwise. * Also returns false for super interfaces of AnyType. */ export function isAnyType(node: core.AbstractWrapperNode) : node is AnyType { return node.kind() == "AnyType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for NumberType. Returns true if node is instance of NumberType. Returns false otherwise. * Also returns false for super interfaces of NumberType. */ export function isNumberType(node: core.AbstractWrapperNode) : node is NumberType { return node.kind() == "NumberType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for IntegerType. Returns true if node is instance of IntegerType. Returns false otherwise. * Also returns false for super interfaces of IntegerType. */ export function isIntegerType(node: core.AbstractWrapperNode) : node is IntegerType { return node.kind() == "IntegerType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for NullType. Returns true if node is instance of NullType. Returns false otherwise. * Also returns false for super interfaces of NullType. */ export function isNullType(node: core.AbstractWrapperNode) : node is NullType { return node.kind() == "NullType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for TimeOnlyType. Returns true if node is instance of TimeOnlyType. Returns false otherwise. * Also returns false for super interfaces of TimeOnlyType. */ export function isTimeOnlyType(node: core.AbstractWrapperNode) : node is TimeOnlyType { return node.kind() == "TimeOnlyType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for DateOnlyType. Returns true if node is instance of DateOnlyType. Returns false otherwise. * Also returns false for super interfaces of DateOnlyType. */ export function isDateOnlyType(node: core.AbstractWrapperNode) : node is DateOnlyType { return node.kind() == "DateOnlyType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for DateTimeOnlyType. Returns true if node is instance of DateTimeOnlyType. Returns false otherwise. * Also returns false for super interfaces of DateTimeOnlyType. */ export function isDateTimeOnlyType(node: core.AbstractWrapperNode) : node is DateTimeOnlyType { return node.kind() == "DateTimeOnlyType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for DateTimeType. Returns true if node is instance of DateTimeType. Returns false otherwise. * Also returns false for super interfaces of DateTimeType. */ export function isDateTimeType(node: core.AbstractWrapperNode) : node is DateTimeType { return node.kind() == "DateTimeType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for FileType. Returns true if node is instance of FileType. Returns false otherwise. * Also returns false for super interfaces of FileType. */ export function isFileType(node: core.AbstractWrapperNode) : node is FileType { return node.kind() == "FileType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for BooleanType. Returns true if node is instance of BooleanType. Returns false otherwise. * Also returns false for super interfaces of BooleanType. */ export function isBooleanType(node: core.AbstractWrapperNode) : node is BooleanType { return node.kind() == "BooleanType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for AnnotationTarget. Returns true if node is instance of AnnotationTarget. Returns false otherwise. * Also returns false for super interfaces of AnnotationTarget. */ export function isAnnotationTarget(node: core.AbstractWrapperNode) : node is AnnotationTarget { return node.kind() == "AnnotationTarget" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for TraitRef. Returns true if node is instance of TraitRef. Returns false otherwise. * Also returns false for super interfaces of TraitRef. */ export function isTraitRef(node: core.AbstractWrapperNode) : node is TraitRef { return node.kind() == "TraitRef" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for Trait. Returns true if node is instance of Trait. Returns false otherwise. * Also returns false for super interfaces of Trait. */ export function isTrait(node: core.AbstractWrapperNode) : node is Trait { return node.kind() == "Trait" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for MethodBase. Returns true if node is instance of MethodBase. Returns false otherwise. * Also returns false for super interfaces of MethodBase. */ export function isMethodBase(node: core.AbstractWrapperNode) : node is MethodBase { return node.kind() == "MethodBase" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for Operation. Returns true if node is instance of Operation. Returns false otherwise. * Also returns false for super interfaces of Operation. */ export function isOperation(node: core.AbstractWrapperNode) : node is Operation { return node.kind() == "Operation" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for TypeDeclaration. Returns true if node is instance of TypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of TypeDeclaration. */ export function isTypeDeclaration(node: core.AbstractWrapperNode) : node is TypeDeclaration { return node.kind() == "TypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for ModelLocation. Returns true if node is instance of ModelLocation. Returns false otherwise. * Also returns false for super interfaces of ModelLocation. */ export function isModelLocation(node: core.AbstractWrapperNode) : node is ModelLocation { return node.kind() == "ModelLocation" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for LocationKind. Returns true if node is instance of LocationKind. Returns false otherwise. * Also returns false for super interfaces of LocationKind. */ export function isLocationKind(node: core.AbstractWrapperNode) : node is LocationKind { return node.kind() == "LocationKind" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for ExampleSpec. Returns true if node is instance of ExampleSpec. Returns false otherwise. * Also returns false for super interfaces of ExampleSpec. */ export function isExampleSpec(node: core.AbstractWrapperNode) : node is ExampleSpec { return node.kind() == "ExampleSpec" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for UsesDeclaration. Returns true if node is instance of UsesDeclaration. Returns false otherwise. * Also returns false for super interfaces of UsesDeclaration. */ export function isUsesDeclaration(node: core.AbstractWrapperNode) : node is UsesDeclaration { return node.kind() == "UsesDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for XMLFacetInfo. Returns true if node is instance of XMLFacetInfo. Returns false otherwise. * Also returns false for super interfaces of XMLFacetInfo. */ export function isXMLFacetInfo(node: core.AbstractWrapperNode) : node is XMLFacetInfo { return node.kind() == "XMLFacetInfo" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for ArrayTypeDeclaration. Returns true if node is instance of ArrayTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of ArrayTypeDeclaration. */ export function isArrayTypeDeclaration(node: core.AbstractWrapperNode) : node is ArrayTypeDeclaration { return node.kind() == "ArrayTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for UnionTypeDeclaration. Returns true if node is instance of UnionTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of UnionTypeDeclaration. */ export function isUnionTypeDeclaration(node: core.AbstractWrapperNode) : node is UnionTypeDeclaration { return node.kind() == "UnionTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for ObjectTypeDeclaration. Returns true if node is instance of ObjectTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of ObjectTypeDeclaration. */ export function isObjectTypeDeclaration(node: core.AbstractWrapperNode) : node is ObjectTypeDeclaration { return node.kind() == "ObjectTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for StringTypeDeclaration. Returns true if node is instance of StringTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of StringTypeDeclaration. */ export function isStringTypeDeclaration(node: core.AbstractWrapperNode) : node is StringTypeDeclaration { return node.kind() == "StringTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for BooleanTypeDeclaration. Returns true if node is instance of BooleanTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of BooleanTypeDeclaration. */ export function isBooleanTypeDeclaration(node: core.AbstractWrapperNode) : node is BooleanTypeDeclaration { return node.kind() == "BooleanTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for NumberTypeDeclaration. Returns true if node is instance of NumberTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of NumberTypeDeclaration. */ export function isNumberTypeDeclaration(node: core.AbstractWrapperNode) : node is NumberTypeDeclaration { return node.kind() == "NumberTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for IntegerTypeDeclaration. Returns true if node is instance of IntegerTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of IntegerTypeDeclaration. */ export function isIntegerTypeDeclaration(node: core.AbstractWrapperNode) : node is IntegerTypeDeclaration { return node.kind() == "IntegerTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for DateOnlyTypeDeclaration. Returns true if node is instance of DateOnlyTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of DateOnlyTypeDeclaration. */ export function isDateOnlyTypeDeclaration(node: core.AbstractWrapperNode) : node is DateOnlyTypeDeclaration { return node.kind() == "DateOnlyTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for TimeOnlyTypeDeclaration. Returns true if node is instance of TimeOnlyTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of TimeOnlyTypeDeclaration. */ export function isTimeOnlyTypeDeclaration(node: core.AbstractWrapperNode) : node is TimeOnlyTypeDeclaration { return node.kind() == "TimeOnlyTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for DateTimeOnlyTypeDeclaration. Returns true if node is instance of DateTimeOnlyTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of DateTimeOnlyTypeDeclaration. */ export function isDateTimeOnlyTypeDeclaration(node: core.AbstractWrapperNode) : node is DateTimeOnlyTypeDeclaration { return node.kind() == "DateTimeOnlyTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for DateTimeTypeDeclaration. Returns true if node is instance of DateTimeTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of DateTimeTypeDeclaration. */ export function isDateTimeTypeDeclaration(node: core.AbstractWrapperNode) : node is DateTimeTypeDeclaration { return node.kind() == "DateTimeTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for FileTypeDeclaration. Returns true if node is instance of FileTypeDeclaration. Returns false otherwise. * Also returns false for super interfaces of FileTypeDeclaration. */ export function isFileTypeDeclaration(node: core.AbstractWrapperNode) : node is FileTypeDeclaration { return node.kind() == "FileTypeDeclaration" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for Response. Returns true if node is instance of Response. Returns false otherwise. * Also returns false for super interfaces of Response. */ export function isResponse(node: core.AbstractWrapperNode) : node is Response { return node.kind() == "Response" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for SecuritySchemePart. Returns true if node is instance of SecuritySchemePart. Returns false otherwise. * Also returns false for super interfaces of SecuritySchemePart. */ export function isSecuritySchemePart(node: core.AbstractWrapperNode) : node is SecuritySchemePart { return node.kind() == "SecuritySchemePart" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for SecuritySchemeRef. Returns true if node is instance of SecuritySchemeRef. Returns false otherwise. * Also returns false for super interfaces of SecuritySchemeRef. */ export function isSecuritySchemeRef(node: core.AbstractWrapperNode) : node is SecuritySchemeRef { return node.kind() == "SecuritySchemeRef" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for AbstractSecurityScheme. Returns true if node is instance of AbstractSecurityScheme. Returns false otherwise. * Also returns false for super interfaces of AbstractSecurityScheme. */ export function isAbstractSecurityScheme(node: core.AbstractWrapperNode) : node is AbstractSecurityScheme { return node.kind() == "AbstractSecurityScheme" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for SecuritySchemeSettings. Returns true if node is instance of SecuritySchemeSettings. Returns false otherwise. * Also returns false for super interfaces of SecuritySchemeSettings. */ export function isSecuritySchemeSettings(node: core.AbstractWrapperNode) : node is SecuritySchemeSettings { return node.kind() == "SecuritySchemeSettings" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for OAuth1SecuritySchemeSettings. Returns true if node is instance of OAuth1SecuritySchemeSettings. Returns false otherwise. * Also returns false for super interfaces of OAuth1SecuritySchemeSettings. */ export function isOAuth1SecuritySchemeSettings(node: core.AbstractWrapperNode) : node is OAuth1SecuritySchemeSettings { return node.kind() == "OAuth1SecuritySchemeSettings" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for OAuth2SecuritySchemeSettings. Returns true if node is instance of OAuth2SecuritySchemeSettings. Returns false otherwise. * Also returns false for super interfaces of OAuth2SecuritySchemeSettings. */ export function isOAuth2SecuritySchemeSettings(node: core.AbstractWrapperNode) : node is OAuth2SecuritySchemeSettings { return node.kind() == "OAuth2SecuritySchemeSettings" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for OAuth2SecurityScheme. Returns true if node is instance of OAuth2SecurityScheme. Returns false otherwise. * Also returns false for super interfaces of OAuth2SecurityScheme. */ export function isOAuth2SecurityScheme(node: core.AbstractWrapperNode) : node is OAuth2SecurityScheme { return node.kind() == "OAuth2SecurityScheme" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for OAuth1SecurityScheme. Returns true if node is instance of OAuth1SecurityScheme. Returns false otherwise. * Also returns false for super interfaces of OAuth1SecurityScheme. */ export function isOAuth1SecurityScheme(node: core.AbstractWrapperNode) : node is OAuth1SecurityScheme { return node.kind() == "OAuth1SecurityScheme" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for PassThroughSecurityScheme. Returns true if node is instance of PassThroughSecurityScheme. Returns false otherwise. * Also returns false for super interfaces of PassThroughSecurityScheme. */ export function isPassThroughSecurityScheme(node: core.AbstractWrapperNode) : node is PassThroughSecurityScheme { return node.kind() == "PassThroughSecurityScheme" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for BasicSecurityScheme. Returns true if node is instance of BasicSecurityScheme. Returns false otherwise. * Also returns false for super interfaces of BasicSecurityScheme. */ export function isBasicSecurityScheme(node: core.AbstractWrapperNode) : node is BasicSecurityScheme { return node.kind() == "BasicSecurityScheme" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for DigestSecurityScheme. Returns true if node is instance of DigestSecurityScheme. Returns false otherwise. * Also returns false for super interfaces of DigestSecurityScheme. */ export function isDigestSecurityScheme(node: core.AbstractWrapperNode) : node is DigestSecurityScheme { return node.kind() == "DigestSecurityScheme" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for CustomSecurityScheme. Returns true if node is instance of CustomSecurityScheme. Returns false otherwise. * Also returns false for super interfaces of CustomSecurityScheme. */ export function isCustomSecurityScheme(node: core.AbstractWrapperNode) : node is CustomSecurityScheme { return node.kind() == "CustomSecurityScheme" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for Method. Returns true if node is instance of Method. Returns false otherwise. * Also returns false for super interfaces of Method. */ export function isMethod(node: core.AbstractWrapperNode) : node is Method { return node.kind() == "Method" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for ResourceTypeRef. Returns true if node is instance of ResourceTypeRef. Returns false otherwise. * Also returns false for super interfaces of ResourceTypeRef. */ export function isResourceTypeRef(node: core.AbstractWrapperNode) : node is ResourceTypeRef { return node.kind() == "ResourceTypeRef" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for ResourceType. Returns true if node is instance of ResourceType. Returns false otherwise. * Also returns false for super interfaces of ResourceType. */ export function isResourceType(node: core.AbstractWrapperNode) : node is ResourceType { return node.kind() == "ResourceType" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for ResourceBase. Returns true if node is instance of ResourceBase. Returns false otherwise. * Also returns false for super interfaces of ResourceBase. */ export function isResourceBase(node: core.AbstractWrapperNode) : node is ResourceBase { return node.kind() == "ResourceBase" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for Resource. Returns true if node is instance of Resource. Returns false otherwise. * Also returns false for super interfaces of Resource. */ export function isResource(node: core.AbstractWrapperNode) : node is Resource { return node.kind() == "Resource" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for DocumentationItem. Returns true if node is instance of DocumentationItem. Returns false otherwise. * Also returns false for super interfaces of DocumentationItem. */ export function isDocumentationItem(node: core.AbstractWrapperNode) : node is DocumentationItem { return node.kind() == "DocumentationItem" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for Library. Returns true if node is instance of Library. Returns false otherwise. * Also returns false for super interfaces of Library. */ export function isLibrary(node: core.AbstractWrapperNode) : node is Library { return node.kind() == "Library" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for Overlay. Returns true if node is instance of Overlay. Returns false otherwise. * Also returns false for super interfaces of Overlay. */ export function isOverlay(node: core.AbstractWrapperNode) : node is Overlay { return node.kind() == "Overlay" && node.RAMLVersion() == "RAML10"; } /** * Custom type guard for Extension. Returns true if node is instance of Extension. Returns false otherwise. * Also returns false for super interfaces of Extension. */ export function isExtension(node: core.AbstractWrapperNode) : node is Extension { return node.kind() == "Extension" && node.RAMLVersion() == "RAML10"; } /** * Check if the AST node represents fragment */ export function isFragment(node:Trait|TypeDeclaration|ExampleSpec|ResourceType|DocumentationItem):boolean{ return node.highLevel().parent()==null; } /** * Convert fragment representing node to FragmentDeclaration instance. */ export function asFragment(node:Trait|TypeDeclaration|ExampleSpec|ResourceType|DocumentationItem):FragmentDeclaration{ return isFragment(node)?<FragmentDeclaration><any>node:null; }
the_stack
import type { QueryClient } from "../client.ts"; import { Query, QueryArguments, QueryArrayResult, QueryConfig, QueryObjectConfig, QueryObjectResult, QueryResult, ResultType, templateStringToQuery, } from "./query.ts"; import { isTemplateString } from "../utils/utils.ts"; import { PostgresError, TransactionError } from "../client/error.ts"; export class Savepoint { /** * This is the count of the current savepoint instances in the transaction */ #instance_count = 0; #release_callback: (name: string) => Promise<void>; #update_callback: (name: string) => Promise<void>; constructor( public readonly name: string, update_callback: (name: string) => Promise<void>, release_callback: (name: string) => Promise<void>, ) { this.#release_callback = release_callback; this.#update_callback = update_callback; } get instances() { return this.#instance_count; } /** * Releasing a savepoint will remove it's last instance in the transaction * * ```ts * const savepoint = await transaction.savepoint("n1"); * await savepoint.release(); * transaction.rollback(savepoint); // Error, can't rollback because the savepoint was released * ``` * * It will also allow you to set the savepoint to the position it had before the last update * * * ```ts * const savepoint = await transaction.savepoint("n1"); * await savepoint.update(); * await savepoint.release(); // This drops the update of the last statement * transaction.rollback(savepoint); // Will rollback to the first instance of the savepoint * ``` * * This function will throw if there are no savepoint instances to drop */ async release() { if (this.#instance_count === 0) { throw new Error("This savepoint has no instances to release"); } await this.#release_callback(this.name); --this.#instance_count; } /** * Updating a savepoint will update its position in the transaction execution * * ```ts * const savepoint = await transaction.savepoint("n1"); * transaction.queryArray`INSERT INTO MY_TABLE (X) VALUES (${my_value})`; * await savepoint.update(); // Rolling back will now return you to this point on the transaction * ``` * * You can also undo a savepoint update by using the `release` method * * ```ts * const savepoint = await transaction.savepoint("n1"); * transaction.queryArray`DELETE FROM VERY_IMPORTANT_TABLE`; * await savepoint.update(); // Oops, shouldn't have updated the savepoint * await savepoint.release(); // This will undo the last update and return the savepoint to the first instance * await transaction.rollback(); // Will rollback before the table was deleted * ``` */ async update() { await this.#update_callback(this.name); ++this.#instance_count; } } type IsolationLevel = "read_committed" | "repeatable_read" | "serializable"; export type TransactionOptions = { isolation_level?: IsolationLevel; read_only?: boolean; snapshot?: string; }; export class Transaction { #client: QueryClient; #executeQuery: (query: Query<ResultType>) => Promise<QueryResult>; #isolation_level: IsolationLevel; #read_only: boolean; #savepoints: Savepoint[] = []; #snapshot?: string; #updateClientLock: (name: string | null) => void; constructor( public name: string, options: TransactionOptions | undefined, client: QueryClient, execute_query_callback: (query: Query<ResultType>) => Promise<QueryResult>, update_client_lock_callback: (name: string | null) => void, ) { this.#client = client; this.#executeQuery = execute_query_callback; this.#isolation_level = options?.isolation_level ?? "read_committed"; this.#read_only = options?.read_only ?? false; this.#snapshot = options?.snapshot; this.#updateClientLock = update_client_lock_callback; } get isolation_level() { return this.#isolation_level; } get savepoints() { return this.#savepoints; } /** * This method will throw if the transaction opened in the client doesn't match this one */ #assertTransactionOpen() { if (this.#client.session.current_transaction !== this.name) { throw new Error( `This transaction has not been started yet, make sure to use the "begin" method to do so`, ); } } #resetTransaction() { this.#savepoints = []; } /** * The begin method will officially begin the transaction, and it must be called before * any query or transaction operation is executed in order to lock the session * ```ts * const transaction = client.createTransaction("transaction_name"); * await transaction.begin(); // Session is locked, transaction operations are now safe * // Important operations * await transaction.commit(); // Session is unlocked, external operations can now take place * ``` * https://www.postgresql.org/docs/14/sql-begin.html */ async begin() { if (this.#client.session.current_transaction !== null) { if (this.#client.session.current_transaction === this.name) { throw new Error( "This transaction is already open", ); } throw new Error( `This client already has an ongoing transaction "${this.#client.session.current_transaction}"`, ); } let isolation_level; switch (this.#isolation_level) { case "read_committed": { isolation_level = "READ COMMITTED"; break; } case "repeatable_read": { isolation_level = "REPEATABLE READ"; break; } case "serializable": { isolation_level = "SERIALIZABLE"; break; } default: throw new Error( `Unexpected isolation level "${this.#isolation_level}"`, ); } let permissions; if (this.#read_only) { permissions = "READ ONLY"; } else { permissions = "READ WRITE"; } let snapshot = ""; if (this.#snapshot) { snapshot = `SET TRANSACTION SNAPSHOT '${this.#snapshot}'`; } try { await this.#client.queryArray( `BEGIN ${permissions} ISOLATION LEVEL ${isolation_level};${snapshot}`, ); } catch (e) { if (e instanceof PostgresError) { throw new TransactionError(this.name, e); } else { throw e; } } this.#updateClientLock(this.name); } /** * The commit method will make permanent all changes made to the database in the * current transaction and end the current transaction * * ```ts * await transaction.begin(); * // Important operations * await transaction.commit(); // Will terminate the transaction and save all changes * ``` * * The commit method allows you to specify a "chain" option, that allows you to both commit the current changes and * start a new with the same transaction parameters in a single statement * * ```ts * // ... * // Transaction operations I want to commit * await transaction.commit({ chain: true }); // All changes are saved, following statements will be executed inside a transaction * await transaction.query`DELETE SOMETHING FROM SOMEWHERE`; // Still inside the transaction * await transaction.commit(); // The transaction finishes for good * ``` * * https://www.postgresql.org/docs/14/sql-commit.html */ async commit(options?: { chain?: boolean }) { this.#assertTransactionOpen(); const chain = options?.chain ?? false; try { await this.queryArray(`COMMIT ${chain ? "AND CHAIN" : ""}`); } catch (e) { if (e instanceof PostgresError) { throw new TransactionError(this.name, e); } else { throw e; } } this.#resetTransaction(); if (!chain) { this.#updateClientLock(null); } } /** * This method will search for the provided savepoint name and return a * reference to the requested savepoint, otherwise it will return undefined */ getSavepoint(name: string): Savepoint | undefined { return this.#savepoints.find((sv) => sv.name === name.toLowerCase()); } /** * This method will list you all of the active savepoints in this transaction */ getSavepoints(): string[] { return this.#savepoints .filter(({ instances }) => instances > 0) .map(({ name }) => name); } /** * This method returns the snapshot id of the on going transaction, allowing you to share * the snapshot state between two transactions * * ```ts * const snapshot = await transaction_1.getSnapshot(); * const transaction_2 = client_2.createTransaction("new_transaction", { isolation_level: "repeatable_read", snapshot }); * // transaction_2 now shares the same starting state that transaction_1 had * ``` * https://www.postgresql.org/docs/14/functions-admin.html#FUNCTIONS-SNAPSHOT-SYNCHRONIZATION */ async getSnapshot(): Promise<string> { this.#assertTransactionOpen(); const { rows } = await this.queryObject<{ snapshot: string }> `SELECT PG_EXPORT_SNAPSHOT() AS SNAPSHOT;`; return rows[0].snapshot; } /** * This method allows executed queries to be retrieved as array entries. * It supports a generic interface in order to type the entries retrieved by the query * * ```ts * const {rows} = await transaction.queryArray( * "SELECT ID, NAME FROM CLIENTS" * ); // Array<unknown[]> * ``` * * You can pass type arguments to the query in order to hint TypeScript what the return value will be * ```ts * const {rows} = await transaction.queryArray<[number, string]>( * "SELECT ID, NAME FROM CLIENTS" * ); // Array<[number, string]> * ``` * * It also allows you to execute prepared stamements with template strings * * ```ts * const id = 12; * // Array<[number, string]> * const {rows} = await transaction.queryArray<[number, string]>`SELECT ID, NAME FROM CLIENTS WHERE ID = ${id}`; * ``` */ async queryArray<T extends Array<unknown>>( query: string, ...args: QueryArguments ): Promise<QueryArrayResult<T>>; async queryArray<T extends Array<unknown>>( config: QueryConfig, ): Promise<QueryArrayResult<T>>; async queryArray<T extends Array<unknown>>( strings: TemplateStringsArray, ...args: QueryArguments ): Promise<QueryArrayResult<T>>; async queryArray<T extends Array<unknown> = Array<unknown>>( query_template_or_config: TemplateStringsArray | string | QueryConfig, ...args: QueryArguments ): Promise<QueryArrayResult<T>> { this.#assertTransactionOpen(); let query: Query<ResultType.ARRAY>; if (typeof query_template_or_config === "string") { query = new Query(query_template_or_config, ResultType.ARRAY, ...args); } else if (isTemplateString(query_template_or_config)) { query = templateStringToQuery( query_template_or_config, args, ResultType.ARRAY, ); } else { query = new Query(query_template_or_config, ResultType.ARRAY); } try { return await this.#executeQuery(query) as QueryArrayResult<T>; } catch (e) { if (e instanceof PostgresError) { await this.commit(); throw new TransactionError(this.name, e); } else { throw e; } } } /** * This method allows executed queries to be retrieved as object entries. * It supports a generic interface in order to type the entries retrieved by the query * * ```ts * const {rows} = await transaction.queryObject( * "SELECT ID, NAME FROM CLIENTS" * ); // Record<string, unknown> * * const {rows} = await transaction.queryObject<{id: number, name: string}>( * "SELECT ID, NAME FROM CLIENTS" * ); // Array<{id: number, name: string}> * ``` * * You can also map the expected results to object fields using the configuration interface. * This will be assigned in the order they were provided * * ```ts * const {rows} = await transaction.queryObject( * "SELECT ID, NAME FROM CLIENTS" * ); * * console.log(rows); // [{id: 78, name: "Frank"}, {id: 15, name: "Sarah"}] * * const {rows} = await transaction.queryObject({ * text: "SELECT ID, NAME FROM CLIENTS", * fields: ["personal_id", "complete_name"], * }); * * console.log(rows); // [{personal_id: 78, complete_name: "Frank"}, {personal_id: 15, complete_name: "Sarah"}] * ``` * * It also allows you to execute prepared stamements with template strings * * ```ts * const id = 12; * // Array<{id: number, name: string}> * const {rows} = await transaction.queryObject<{id: number, name: string}>`SELECT ID, NAME FROM CLIENTS WHERE ID = ${id}`; * ``` */ async queryObject<T>( query: string, ...args: QueryArguments ): Promise<QueryObjectResult<T>>; async queryObject<T>( config: QueryObjectConfig, ): Promise<QueryObjectResult<T>>; async queryObject<T>( query: TemplateStringsArray, ...args: QueryArguments ): Promise<QueryObjectResult<T>>; async queryObject< T = Record<string, unknown>, >( query_template_or_config: | string | QueryObjectConfig | TemplateStringsArray, ...args: QueryArguments ): Promise<QueryObjectResult<T>> { this.#assertTransactionOpen(); let query: Query<ResultType.OBJECT>; if (typeof query_template_or_config === "string") { query = new Query(query_template_or_config, ResultType.OBJECT, ...args); } else if (isTemplateString(query_template_or_config)) { query = templateStringToQuery( query_template_or_config, args, ResultType.OBJECT, ); } else { query = new Query( query_template_or_config as QueryObjectConfig, ResultType.OBJECT, ); } try { return await this.#executeQuery(query) as QueryObjectResult<T>; } catch (e) { if (e instanceof PostgresError) { await this.commit(); throw new TransactionError(this.name, e); } else { throw e; } } } /** * Rollbacks are a mechanism to undo transaction operations without compromising the data that was modified during * the transaction * * A rollback can be executed the following way * ```ts * // ... * // Very very important operations that went very, very wrong * await transaction.rollback(); // Like nothing ever happened * ``` * * Calling a rollback without arguments will terminate the current transaction and undo all changes, * but it can be used in conjuction with the savepoint feature to rollback specific changes like the following * * ```ts * // ... * // Important operations I don't want to rollback * const savepoint = await transaction.savepoint("before_disaster"); * await transaction.queryArray`UPDATE MY_TABLE SET X = 0`; // Oops, update without where * await transaction.rollback(savepoint); // "before_disaster" would work as well * // Everything that happened between the savepoint and the rollback gets undone * await transaction.commit(); // Commits all other changes * ``` * * The rollback method allows you to specify a "chain" option, that allows you to not only undo the current transaction * but to restart it with the same parameters in a single statement * * ```ts * // ... * // Transaction operations I want to undo * await transaction.rollback({ chain: true }); // All changes are undone, but the following statements will be executed inside a transaction as well * await transaction.query`DELETE SOMETHING FROM SOMEWHERE`; // Still inside the transaction * await transaction.commit(); // The transaction finishes for good * ``` * * However, the "chain" option can't be used alongside a savepoint, even though they are similar * * A savepoint is meant to reset progress up to a certain point, while a chained rollback is meant to reset all progress * and start from scratch * * ```ts * await transaction.rollback({ chain: true, savepoint: my_savepoint }); // Error, can't both return to savepoint and reset transaction * ``` * https://www.postgresql.org/docs/14/sql-rollback.html */ async rollback(savepoint?: string | Savepoint): Promise<void>; async rollback(options?: { savepoint?: string | Savepoint }): Promise<void>; async rollback(options?: { chain?: boolean }): Promise<void>; async rollback( savepoint_or_options?: string | Savepoint | { savepoint?: string | Savepoint; } | { chain?: boolean }, ): Promise<void> { this.#assertTransactionOpen(); let savepoint_option: Savepoint | string | undefined; if ( typeof savepoint_or_options === "string" || savepoint_or_options instanceof Savepoint ) { savepoint_option = savepoint_or_options; } else { savepoint_option = (savepoint_or_options as { savepoint?: string | Savepoint })?.savepoint; } let savepoint_name: string | undefined; if (savepoint_option instanceof Savepoint) { savepoint_name = savepoint_option.name; } else if (typeof savepoint_option === "string") { savepoint_name = savepoint_option.toLowerCase(); } let chain_option = false; if (typeof savepoint_or_options === "object") { chain_option = (savepoint_or_options as { chain?: boolean })?.chain ?? false; } if (chain_option && savepoint_name) { throw new Error( "The chain option can't be used alongside a savepoint on a rollback operation", ); } // If a savepoint is provided, rollback to that savepoint, continue the transaction if (typeof savepoint_option !== "undefined") { const ts_savepoint = this.#savepoints.find(({ name }) => name === savepoint_name ); if (!ts_savepoint) { throw new Error( `There is no "${savepoint_name}" savepoint registered in this transaction`, ); } if (!ts_savepoint.instances) { throw new Error( `There are no savepoints of "${savepoint_name}" left to rollback to`, ); } await this.queryArray(`ROLLBACK TO ${savepoint_name}`); return; } // If no savepoint is provided, rollback the whole transaction and check for the chain operator // in order to decide whether to restart the transaction or end it try { await this.queryArray(`ROLLBACK ${chain_option ? "AND CHAIN" : ""}`); } catch (e) { if (e instanceof PostgresError) { await this.commit(); throw new TransactionError(this.name, e); } else { throw e; } } this.#resetTransaction(); if (!chain_option) { this.#updateClientLock(null); } } /** * This method will generate a savepoint, which will allow you to reset transaction states * to a previous point of time * * Each savepoint has a unique name used to identify it, and it must abide the following rules * * - Savepoint names must start with a letter or an underscore * - Savepoint names are case insensitive * - Savepoint names can't be longer than 63 characters * - Savepoint names can only have alphanumeric characters * * A savepoint can be easily created like this * ```ts * const savepoint = await transaction.save("MY_savepoint"); // returns a `Savepoint` with name "my_savepoint" * await transaction.rollback(savepoint); * await savepoint.release(); // The savepoint will be removed * ``` * All savepoints can have multiple positions in a transaction, and you can change or update * this positions by using the `update` and `release` methods * ```ts * const savepoint = await transaction.save("n1"); * await transaction.queryArray`INSERT INTO MY_TABLE VALUES (${'A'}, ${2})`; * await savepoint.update(); // The savepoint will continue from here * await transaction.queryArray`DELETE FROM MY_TABLE`; * await transaction.rollback(savepoint); // The transaction will rollback before the delete, but after the insert * await savepoint.release(); // The last savepoint will be removed, the original one will remain * await transaction.rollback(savepoint); // It rolls back before the insert * await savepoint.release(); // All savepoints are released * ``` * * Creating a new savepoint with an already used name will return you a reference to * the original savepoint * ```ts * const savepoint_a = await transaction.save("a"); * await transaction.queryArray`DELETE FROM MY_TABLE`; * const savepoint_b = await transaction.save("a"); // They will be the same savepoint, but the savepoint will be updated to this position * await transaction.rollback(savepoint_a); // Rolls back to savepoint_b * ``` * https://www.postgresql.org/docs/14/sql-savepoint.html */ async savepoint(name: string): Promise<Savepoint> { this.#assertTransactionOpen(); if (!/^[a-zA-Z_]{1}[\w]{0,62}$/.test(name)) { if (!Number.isNaN(Number(name[0]))) { throw new Error("The savepoint name can't begin with a number"); } if (name.length > 63) { throw new Error( "The savepoint name can't be longer than 63 characters", ); } throw new Error( "The savepoint name can only contain alphanumeric characters", ); } name = name.toLowerCase(); let savepoint = this.#savepoints.find((sv) => sv.name === name); if (savepoint) { try { await savepoint.update(); } catch (e) { if (e instanceof PostgresError) { await this.commit(); throw new TransactionError(this.name, e); } else { throw e; } } } else { savepoint = new Savepoint( name, async (name: string) => { await this.queryArray(`SAVEPOINT ${name}`); }, async (name: string) => { await this.queryArray(`RELEASE SAVEPOINT ${name}`); }, ); try { await savepoint.update(); } catch (e) { if (e instanceof PostgresError) { await this.commit(); throw new TransactionError(this.name, e); } else { throw e; } } this.#savepoints.push(savepoint); } return savepoint; } }
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 Describes how to render the data sent from the server in a request for a report */ namespace VRS { /** * The options passed to ReportPropertyHandler callbacks. */ export interface ReportRender_Options { unitDisplayPreferences: UnitDisplayPreferences; distinguishOnGround?: boolean; showUnits?: boolean; alwaysShowEndDate?: boolean; plotterOptions?: AircraftPlotterOptions; justShowStartTime?: boolean; } /** * The settings to pass when createing a new instance of ReportPropertyHandler. */ export interface ReportPropertyHandler_Settings { /** * The property that this object handles. */ property: ReportAircraftOrFlightPropertyEnum; /** * The surfaces that the property can be rendered onto. If not supplied then it is assumed to be List and DetailBody. */ surfaces?: ReportSurfaceBitFlags; /** * The key into VRS.$$ for the property's label. Uses headingKey if missing. */ labelKey?: string; /** * The key into VRS.$$ for the property's list heading. Uses labelKey if missing. */ headingKey?: string; /** * The key into VRS.$$ for the property's options label. Uses labelKey or headingKey if missing. */ optionsLabelKey?: string; /** * The VRS.Alignment enum describing the alignment for column headings - uses alignment if not supplied. */ headingAlignment?: AlignmentEnum; /** * The VRS.Alignment enum describing the alignment for values in columns - uses alignment if not supplied. */ contentAlignment?: AlignmentEnum; /** * The VRS.Alignment enum describing the alignment for headings and column values. */ alignment?: AlignmentEnum; /** * An optional fixed width as a CSS width string (e.g. '20px' or '6em') when rendering within columns. */ fixedWidth?: (surface?: ReportSurfaceBitFlags) => string; /** * A mandatory method that returns true if the JSON passed across has a value for the property. */ hasValue: (aircraftOrFlight: IReportAircraft | IReportFlight) => boolean; /** * Takes a JSON object and an options object and returns the text content that represents the property. */ contentCallback?: (aircraftOrFlight: IReportAircraft | IReportFlight, options?: ReportRender_Options, surface?: ReportSurfaceBitFlags) => string; /** * Takes a JSON object and options object and returns HTML that represents the property. */ renderCallback?: (aircraftOrFlight: IReportAircraft | IReportFlight, options?: ReportRender_Options, surface?: ReportSurfaceBitFlags) => string; /** * Takes a JSON object and options object and returns the tooltip text for the property. If not supplied then the property has no tooltip. */ tooltipCallback?: (aircraftOrFlight: IReportAircraft | IReportFlight, options?: ReportRender_Options) => string; /** * True if the content takes more than one line of text to display, false if it does not. Defaults to false. */ isMultiLine?: boolean; /** * An optional method that returns true if the label is not to be shown on this surface. Default returns false. */ suppressLabelCallback?: (surface: ReportSurfaceBitFlags) => boolean; /** * The sort column corresponding to this property, if any. Default is undefined. */ sortColumn?: ReportSortColumnEnum; /** * The grouping value to use when grouping report columns based on sort value. Default is undefined. Mandatory if sortColumn is supplied. */ groupValue?: (aircraftOrFlight: IReportAircraft | IReportFlight) => string | number; /** * Widget support - called after an element has been created for the render property, allows the renderer to add a widget to the element. */ createWidget?: (element: JQuery, surface: ReportSurfaceBitFlags, options: ReportRender_Options) => void; /** * Widget support - renders the property into a widget. */ renderWidget?: (element: JQuery, aircraftOrFlight: IReportAircraft | IReportFlight, options: ReportRender_Options, surface: ReportSurfaceBitFlags) => void; /** * Destroys the widget attached to the element. */ destroyWidget?: (element: JQuery, surface: ReportSurfaceBitFlags) => void; } /** * An object that can handle the rendering of a property in the report. */ export class ReportPropertyHandler { private _HasValue: (aircraftOrFlight: IReportAircraft | IReportFlight) => boolean; private _CreateWidget: (element: JQuery, surface: ReportSurfaceBitFlags, options: ReportRender_Options) => void; private _DestroyWidget: (element: JQuery, surface: ReportSurfaceBitFlags) => void; private _RenderWidget: (element: JQuery, aircraftOrFlight: IReportAircraft | IReportFlight, options: ReportRender_Options, surface: ReportSurfaceBitFlags) => void; private _ContentCallback: (aircraftOrFlight: IReportAircraft | IReportFlight, options?: ReportRender_Options, surface?: ReportSurfaceBitFlags) => string; private _RenderCallback: (aircraftOrFlight: IReportAircraft | IReportFlight, options?: ReportRender_Options, surface?: ReportSurfaceBitFlags) => string; private _TooltipCallback: (aircraftOrFlight: IReportAircraft | IReportFlight, options?: ReportRender_Options) => string; // Kept as public fields for backwards compatibility property: ReportAircraftOrFlightPropertyEnum; surfaces: ReportSurfaceBitFlags; labelKey: string; headingKey: string; optionsLabelKey: string; headingAlignment: AlignmentEnum; contentAlignment: AlignmentEnum; isMultiLine: boolean; fixedWidth: (surface?: ReportSurfaceBitFlags) => string; suppressLabelCallback: (surface: ReportSurfaceBitFlags) => boolean; sortColumn: ReportSortColumnEnum; groupValue: (aircraftOrFlight: IReportAircraft | IReportFlight) => string | number; isAircraftProperty: boolean; isFlightsProperty: boolean; constructor(settings: ReportPropertyHandler_Settings) { this.property = settings.property; this.surfaces = settings.surfaces || (VRS.ReportSurface.List + VRS.ReportSurface.DetailBody); this.labelKey = settings.labelKey || settings.headingKey; this.headingKey = settings.headingKey || settings.labelKey; this.optionsLabelKey = settings.optionsLabelKey || settings.labelKey || settings.headingKey; this.headingAlignment = settings.headingAlignment || settings.alignment || settings.contentAlignment || VRS.Alignment.Left; this.contentAlignment = settings.contentAlignment || settings.alignment || settings.headingAlignment || VRS.Alignment.Left; this.isMultiLine = settings.isMultiLine || false; this.fixedWidth = settings.fixedWidth; this.suppressLabelCallback = settings.suppressLabelCallback || function() { return false; }; this.sortColumn = settings.sortColumn; this.groupValue = settings.groupValue; this.isAircraftProperty = !!VRS.enumHelper.getEnumName(VRS.ReportAircraftProperty, settings.property); this.isFlightsProperty = !this.isAircraftProperty; this._HasValue = settings.hasValue; this._CreateWidget = settings.createWidget; this._DestroyWidget = settings.destroyWidget; this._RenderWidget = settings.renderWidget; this._ContentCallback = settings.contentCallback; this._RenderCallback = settings.renderCallback; this._TooltipCallback = settings.tooltipCallback; } /** * Returns true if the property can be rendered onto the VRS.ReportSurface passed across. */ isSurfaceSupported(surface: ReportSurfaceBitFlags) : boolean { return (this.surfaces & surface) !== 0; } /** * Returns true if the property has a value for the flight or aircraft passed across. */ hasValue(flightJson: IReportFlight) : boolean { var json = this.isAircraftProperty ? flightJson.aircraft : flightJson; return this._HasValue(json); } /** * If the renderer uses a widget then this creates the widget in the element passed across, otherwise it does nothing. */ createWidgetInJQueryElement(jQueryElement: JQuery, surface: ReportSurfaceBitFlags, options: ReportRender_Options) { if(this._CreateWidget) { this._CreateWidget(jQueryElement, surface, options); } } /** * If the renderer uses a widget then this destroys the widget in the element passed across, otherwise it does nothing. */ destroyWidgetInJQueryElement(jQueryElement: JQuery, surface: ReportSurfaceBitFlags) { if(this._DestroyWidget) { this._DestroyWidget(jQueryElement, surface); } } /** * Renders content into the jQuery element passed across. */ renderIntoJQueryElement(jqElement: JQuery, json: IReportAircraft | IReportFlight, options: ReportRender_Options, surface: ReportSurfaceBitFlags) { if(this._ContentCallback) { jqElement.text(this._ContentCallback(json, options, surface)); } else if(this._RenderWidget) { this._RenderWidget(jqElement, json, options, surface); } else { jqElement.html(this._RenderCallback(json, options, surface)); } } /** * Adds a tooltip to the jQuery element passed acros. */ addTooltip(jqElement: JQuery, json: IReportAircraft | IReportFlight, options: ReportRender_Options) { if(this._TooltipCallback) { var text = this._TooltipCallback(json, options); if(text) { jqElement.attr('title', text); } } } } /* * Pre-built report property handlers */ export var reportPropertyHandlers: { [index: string /* ReportAircraftOrFlightPropertyEnum */]: ReportPropertyHandler } = VRS.reportPropertyHandlers || {}; /* * AIRCRAFT PROPERTIES */ VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.AircraftClass] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.AircraftClass, headingKey: 'ListAircraftClass', labelKey: 'AircraftClass', hasValue: function(json: IReportAircraft) { return !!json.acClass; }, contentCallback: function(json: IReportAircraft) { return VRS.format.aircraftClass(json.acClass); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.CofACategory] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.CofACategory, headingKey: 'ListCofACategory', labelKey: 'CofACategory', hasValue: function(json: IReportAircraft) { return !!json.cofACategory; }, contentCallback: function(json: IReportAircraft) { return VRS.format.certOfACategory(json.cofACategory); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.CofAExpiry] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.CofAExpiry, headingKey: 'ListCofAExpiry', labelKey: 'CofAExpiry', hasValue: function(json: IReportAircraft) { return !!json.cofAExpiry; }, contentCallback: function(json: IReportAircraft) { return VRS.format.certOfAExpiry(json.cofAExpiry); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Country] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Country, surfaces: VRS.ReportSurface.List + VRS.ReportSurface.DetailHead, headingKey: 'ListCountry', labelKey: 'Country', hasValue: function(json: IReportAircraft) { return !!json.country; }, contentCallback: function(json: IReportAircraft) { return VRS.format.country(json.country); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.CurrentRegDate] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.CurrentRegDate, headingKey: 'ListCurrentRegDate', labelKey: 'CurrentRegDate', hasValue: function(json: IReportAircraft) { return !!json.curRegDate; }, contentCallback: function(json: IReportAircraft) { return VRS.format.currentRegistrationDate(json.curRegDate); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.DeRegDate] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.DeRegDate, headingKey: 'ListDeRegDate', labelKey: 'DeRegDate', hasValue: function(json: IReportAircraft) { return !!json.deregDate; }, contentCallback: function(json: IReportAircraft) { return VRS.format.deregisteredDate(json.deregDate); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Engines] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Engines, headingKey: 'ListEngines', labelKey: 'Engines', hasValue: function(json: IReportAircraft) { return json.engType !== undefined && json.engines !== undefined; }, contentCallback: function(json: IReportAircraft) { return VRS.format.engines(json.engines, json.engType); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.FirstRegDate] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.FirstRegDate, headingKey: 'ListFirstRegDate', labelKey: 'FirstRegDate', hasValue: function(json: IReportAircraft) { return !!json.firstRegDate; }, contentCallback: function(json: IReportAircraft) { return VRS.format.firstRegistrationDate(json.firstRegDate); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.GenericName] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.GenericName, headingKey: 'ListGenericName', labelKey: 'GenericName', hasValue: function(json: IReportAircraft) { return json.genericName !== undefined; }, contentCallback: function(json: IReportAircraft) { return VRS.format.genericName(json.genericName); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Icao] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Icao, surfaces: VRS.ReportSurface.List + VRS.ReportSurface.DetailHead, headingKey: 'ListIcao', labelKey: 'Icao', hasValue: function(json: IReportAircraft) { return !!json.icao; }, contentCallback: function(json: IReportAircraft) { return VRS.format.icao(json.icao); }, sortColumn: VRS.ReportSortColumn.Icao, groupValue: function(json: IReportAircraft) { return json.icao; } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Interesting] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Interesting, headingKey: 'ListInteresting', labelKey: 'Interesting', hasValue: function(json: IReportAircraft) { return json.interested !== undefined; }, contentCallback: function(json: IReportAircraft) { return VRS.format.userInterested(json.interested); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Manufacturer] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Manufacturer, headingKey: 'ListManufacturer', labelKey: 'Manufacturer', hasValue: function(json: IReportAircraft) { return !!json.manufacturer; }, contentCallback: function(json: IReportAircraft) { return VRS.format.manufacturer(json.manufacturer); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Military] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Military, surfaces: VRS.ReportSurface.List + VRS.ReportSurface.DetailHead, headingKey: 'ListCivOrMil', labelKey: 'CivilOrMilitary', hasValue: function(json: IReportAircraft) { return true; }, // The server doesn't emit the value if it's civilian contentCallback: function(json: IReportAircraft) { return VRS.format.isMilitary(!!json.military); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Model] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Model, surfaces: VRS.ReportSurface.List + VRS.ReportSurface.DetailHead, headingKey: 'ListModel', labelKey: 'Model', hasValue: function(json: IReportAircraft) { return !!json.typ; }, contentCallback: function(json: IReportAircraft) { return VRS.format.model(json.typ); }, sortColumn: VRS.ReportSortColumn.Model, groupValue: function(json: IReportAircraft) { return json.typ; } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.ModelIcao] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.ModelIcao, surfaces: VRS.ReportSurface.List + VRS.ReportSurface.DetailHead, headingKey: 'ListModelIcao', labelKey: 'ModelIcao', hasValue: function(json: IReportAircraft) { return !!json.icaoType; }, contentCallback: function(json: IReportAircraft) { return VRS.format.modelIcao(json.icaoType); }, sortColumn: VRS.ReportSortColumn.ModelIcao, groupValue: function(json: IReportAircraft) { return json.icaoType; } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.ModeSCountry] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.ModeSCountry, headingKey: 'ListModeSCountry', labelKey: 'ModeSCountry', hasValue: function(json: IReportAircraft) { return !!json.modeSCountry; }, contentCallback: function(json: IReportAircraft) { return VRS.format.modeSCountry(json.modeSCountry); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.MTOW] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.MTOW, headingKey: 'ListMaxTakeoffWeight', labelKey: 'MaxTakeoffWeight', hasValue: function(json: IReportAircraft) { return !!json.mtow; }, contentCallback: function(json: IReportAircraft) { return VRS.format.maxTakeoffWeight(json.mtow); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Notes] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Notes, headingKey: 'ListNotes', labelKey: 'Notes', isMultiLine: true, hasValue: function(json: IReportAircraft) { return !!json.notes; }, renderCallback: function(json: IReportAircraft, options: ReportRender_Options, surface: ReportSurfaceBitFlags) { switch(surface) { case VRS.ReportSurface.DetailBody: return VRS.format.userNotesMultiline(json.notes); default: return VRS.stringUtility.htmlEscape(VRS.format.userNotes(json.notes)); } } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Operator] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Operator, surfaces: VRS.ReportSurface.List + VRS.ReportSurface.DetailHead, headingKey: 'ListOperator', labelKey: 'Operator', hasValue: function(json: IReportAircraft) { return !!json.owner; }, contentCallback: function(json: IReportAircraft) { return VRS.format.operator(json.owner); }, sortColumn: VRS.ReportSortColumn.Operator, groupValue: function(json: IReportAircraft) { return json.owner; } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.OperatorFlag] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.OperatorFlag, surfaces: VRS.ReportSurface.List + VRS.ReportSurface.DetailHead, headingKey: 'ListOperatorFlag', labelKey: 'OperatorFlag', headingAlignment: VRS.Alignment.Centre, fixedWidth: function() { return VRS.globalOptions.aircraftOperatorFlagSize.width.toString() + 'px'; }, hasValue: function(json: IReportAircraft) { return !!json.opFlag || !!json.icao || !!json.reg; }, renderCallback: function(json: IReportAircraft) { return VRS.format.operatorIcaoImageHtml(json.owner, json.opFlag, json.icao, json.reg); }, tooltipCallback: function(json: IReportAircraft) { return VRS.format.operatorIcaoAndName(json.owner, json.opFlag); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.OperatorIcao] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.OperatorIcao, headingKey: 'ListOperatorIcao', labelKey: 'OperatorCode', hasValue: function(json: IReportAircraft) { return !!json.opFlag; }, contentCallback: function(json: IReportAircraft) { return VRS.format.operatorIcao(json.opFlag); }, tooltipCallback: function(json: IReportAircraft) { return VRS.format.operatorIcaoAndName(json.owner, json.opFlag); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.OwnershipStatus] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.OwnershipStatus, headingKey: 'ListOwnershipStatus', labelKey: 'OwnershipStatus', hasValue: function(json: IReportAircraft) { return !!json.ownerStatus; }, contentCallback: function(json: IReportAircraft) { return VRS.format.ownershipStatus(json.ownerStatus); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Picture] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Picture, surfaces: VRS.ReportSurface.List + VRS.ReportSurface.DetailBody, headingKey: 'ListPicture', labelKey: 'Picture', headingAlignment: VRS.Alignment.Centre, isMultiLine: true, fixedWidth: function(surface: ReportSurfaceBitFlags) { switch(surface) { case VRS.ReportSurface.List: return VRS.globalOptions.aircraftPictureSizeList.width.toString() + 'px'; default: return null; } }, hasValue: function(json: IReportAircraft) { return json.hasPic; }, suppressLabelCallback: function(surface: ReportSurfaceBitFlags) { return surface === VRS.ReportSurface.DetailBody; }, renderCallback: function(json: IReportAircraft, options: ReportRender_Options, surface: ReportSurfaceBitFlags) { switch(surface) { case VRS.ReportSurface.List: return VRS.format.pictureHtml( json.reg, json.icao, json.picX, json.picY, VRS.globalOptions.aircraftPictureSizeList); case VRS.ReportSurface.DetailBody: return VRS.format.pictureHtml( json.reg, json.icao, json.picX, json.picY, !VRS.globalOptions.isMobile ? VRS.globalOptions.aircraftPictureSizeDesktopDetail : VRS.globalOptions.aircraftPictureSizeMobileDetail, false, true); default: throw 'Unexpected surface ' + surface; } } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.PopularName] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.PopularName, headingKey: 'ListPopularName', labelKey: 'PopularName', hasValue: function(json: IReportAircraft) { return !!json.popularName; }, contentCallback: function(json: IReportAircraft) { return VRS.format.popularName(json.popularName); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.PreviousId] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.PreviousId, headingKey: 'ListPreviousId', labelKey: 'PreviousId', hasValue: function(json: IReportAircraft) { return !!json.previousId; }, contentCallback: function(json: IReportAircraft) { return VRS.format.previousId(json.previousId); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Registration] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Registration, surfaces: VRS.ReportSurface.List + VRS.ReportSurface.DetailHead, headingKey: 'ListRegistration', labelKey: 'Registration', hasValue: function(json: IReportAircraft) { return !!json.reg; }, contentCallback: function(json: IReportAircraft) { return VRS.format.registration(json.reg); }, sortColumn: VRS.ReportSortColumn.Registration, groupValue: function(json: IReportAircraft) { return json.reg; } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.SerialNumber] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.SerialNumber, headingKey: 'ListSerialNumber', labelKey: 'SerialNumber', hasValue: function(json: IReportAircraft) { return !!json.serial; }, contentCallback: function(json: IReportAircraft) { return VRS.format.serial(json.serial); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Silhouette] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Silhouette, headingKey: 'ListModelSilhouette', labelKey: 'Silhouette', surfaces: VRS.ReportSurface.List, headingAlignment: VRS.Alignment.Centre, fixedWidth: function() { return VRS.globalOptions.aircraftSilhouetteSize.width.toString() + 'px'; }, hasValue: function(json: IReportAircraft) { return !!json.icaoType || !!json.icao || !!json.reg; }, renderCallback: function(json: IReportAircraft) { return VRS.format.modelIcaoImageHtml(json.icaoType, json.icao, json.reg); }, tooltipCallback: function(json: IReportAircraft) { return VRS.format.modelIcaoNameAndDetail(json.icaoType, json.typ, json.engines, json.engType, json.species, json.wtc); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Species] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Species, headingKey: 'ListSpecies', labelKey: 'Species', hasValue: function(json: IReportAircraft) { return json.species !== undefined; }, contentCallback: function(json: IReportAircraft) { return VRS.format.species(json.species); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.Status] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.Status, headingKey: 'ListStatus', labelKey: 'Status', hasValue: function(json: IReportAircraft) { return !!json.status; }, contentCallback: function(json: IReportAircraft) { return VRS.format.status(json.status); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.TotalHours] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.TotalHours, headingKey: 'ListTotalHours', labelKey: 'TotalHours', hasValue: function(json: IReportAircraft) { return !!json.totalHours; }, contentCallback: function(json: IReportAircraft) { return VRS.format.totalHours(json.totalHours); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.YearBuilt] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.YearBuilt, headingKey: 'ListYearBuilt', labelKey: 'YearBuilt', hasValue: function(json: IReportAircraft) { return !!json.yearBuilt; }, contentCallback: function(json: IReportAircraft) { return VRS.format.yearBuilt(json.yearBuilt); } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.WakeTurbulenceCategory] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.WakeTurbulenceCategory, headingKey: 'ListWtc', labelKey: 'WakeTurbulenceCategory', hasValue: function(json: IReportAircraft) { return json.wtc !== undefined; }, contentCallback: function(json: IReportAircraft) { return VRS.format.wakeTurbulenceCat(json.wtc, true, false); } }); /* * FLIGHT PROPERTIES */ VRS.reportPropertyHandlers[VRS.ReportFlightProperty.Altitude] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.Altitude, headingKey: 'ListAltitude', labelKey: 'Altitude', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.fAlt !== undefined || json.lAlt !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.altitudeFromTo(json.fAlt, json.fOnGnd, json.lAlt, json.lOnGnd, options.unitDisplayPreferences.getHeightUnit(), options.distinguishOnGround, options.showUnits); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.Callsign] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.Callsign, surfaces: VRS.ReportSurface.List + VRS.ReportSurface.DetailHead, headingKey: 'ListCallsign', labelKey: 'Callsign', hasValue: function(json: IReportFlight) { return !!json.call; }, contentCallback: function(json: IReportFlight) { return VRS.format.callsign(json.call, false, false); }, tooltipCallback: function(json: IReportFlight) { return VRS.format.reportRouteFull(json.call, json.route); }, sortColumn: VRS.ReportSortColumn.Callsign, groupValue: function(json: IReportFlight) { return json.call; } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.CountAdsb] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.CountAdsb, headingKey: 'ListCountAdsb', labelKey: 'CountAdsb', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.cADSB !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.countMessages(json.cADSB); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.CountModeS] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.CountModeS, headingKey: 'ListCountModeS', labelKey: 'CountModeS', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.cMDS !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.countMessages(json.cMDS); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.CountPositions] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.CountPositions, headingKey: 'ListCountPositions', labelKey: 'CountPositions', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.cPOS !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.countMessages(json.cPOS); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.Duration] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.Duration, headingKey: 'ListDuration', labelKey: 'Duration', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.start !== undefined && json.end !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.duration(<any>(json.end) - <any>(json.start), false); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.EndTime] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.EndTime, headingKey: 'ListEndTime', labelKey: 'EndTime', hasValue: function(json: IReportFlight) { return json.end !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.endDateTime(json.start, json.end, false, options.alwaysShowEndDate); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.FirstAltitude] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.FirstAltitude, headingKey: 'ListFirstAltitude', labelKey: 'FirstAltitude', alignment: VRS.Alignment.Right, sortColumn: VRS.ReportSortColumn.FirstAltitude, hasValue: function(json: IReportFlight) { return json.fAlt !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.altitude(json.fAlt, VRS.AltitudeType.Barometric, json.fOnGnd, options.unitDisplayPreferences.getHeightUnit(), options.distinguishOnGround, options.showUnits, false); }, groupValue: function(json: IReportFlight) { return json.fAlt; } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.FirstFlightLevel] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.FirstFlightLevel, headingKey: 'ListFirstFlightLevel', labelKey: 'FirstFlightLevel', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.fAlt !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.flightLevel( json.fAlt, json.fAlt, VRS.AltitudeType.Barometric, json.fOnGnd, options.unitDisplayPreferences.getFlightLevelTransitionAltitude(), options.unitDisplayPreferences.getFlightLevelTransitionHeightUnit(), options.unitDisplayPreferences.getFlightLevelHeightUnit(), options.unitDisplayPreferences.getHeightUnit(), options.distinguishOnGround, options.showUnits, false ); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.FirstHeading] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.FirstHeading, headingKey: 'ListFirstHeading', labelKey: 'FirstHeading', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.fTrk !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.heading(json.fTrk, false, options.showUnits, false); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.FirstLatitude] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.FirstLatitude, headingKey: 'ListFirstLatitude', labelKey: 'FirstLatitude', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.fLat !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.latitude(json.fLat, options.showUnits); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.FirstLongitude] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.FirstLongitude, headingKey: 'ListFirstLongitude', labelKey: 'FirstLongitude', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.fLng !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.longitude(json.fLng, options.showUnits); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.FirstOnGround] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.FirstOnGround, headingKey: 'ListFirstOnGround', labelKey: 'FirstOnGround', hasValue: function(json: IReportFlight) { return json.fOnGnd !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.isOnGround(json.fOnGnd); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.FirstSpeed] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.FirstSpeed, headingKey: 'ListFirstSpeed', labelKey: 'FirstSpeed', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.fSpd !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.speed( json.fSpd, VRS.SpeedType.Ground, options.unitDisplayPreferences.getSpeedUnit(), options.showUnits, false ); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.FirstSquawk] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.FirstSquawk, headingKey: 'ListFirstSquawk', labelKey: 'FirstSquawk', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.fSqk !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.squawk(json.fSqk); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.FirstVerticalSpeed] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.FirstVerticalSpeed, headingKey: 'ListFirstVerticalSpeed', labelKey: 'FirstVerticalSpeed', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.fVsi !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.verticalSpeed(json.fVsi, json.fOnGnd, AltitudeType.Barometric, options.unitDisplayPreferences.getHeightUnit(), options.unitDisplayPreferences.getShowVerticalSpeedPerSecond(), options.showUnits); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.FlightLevel] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.FlightLevel, headingKey: 'ListFlightLevel', labelKey: 'FlightLevel', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.fAlt !== undefined || json.lAlt !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.flightLevelFromTo( json.fAlt, json.fOnGnd, json.lAlt, json.lOnGnd, options.unitDisplayPreferences.getFlightLevelTransitionAltitude(), options.unitDisplayPreferences.getFlightLevelTransitionHeightUnit(), options.unitDisplayPreferences.getFlightLevelHeightUnit(), options.unitDisplayPreferences.getHeightUnit(), options.distinguishOnGround, options.showUnits ); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.HadAlert] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.HadAlert, headingKey: 'ListHadAlert', labelKey: 'HadAlert', hasValue: function(json: IReportFlight) { return json.hAlrt !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.hadAlert(json.hAlrt); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.HadEmergency] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.HadEmergency, headingKey: 'ListHadEmergency', labelKey: 'HadEmergency', hasValue: function(json: IReportFlight) { return json.hEmg !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.hadEmergency(json.hEmg); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.HadSPI] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.HadSPI, headingKey: 'ListHadSPI', labelKey: 'HadSPI', hasValue: function(json: IReportFlight) { return json.hSpi !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.hadSPI(json.hSpi); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.LastAltitude] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.LastAltitude, headingKey: 'ListLastAltitude', labelKey: 'LastAltitude', alignment: VRS.Alignment.Right, sortColumn: VRS.ReportSortColumn.LastAltitude, hasValue: function(json: IReportFlight) { return json.lAlt !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.altitude(json.lAlt, VRS.AltitudeType.Barometric, json.lOnGnd, options.unitDisplayPreferences.getHeightUnit(), options.distinguishOnGround, options.showUnits, false); }, groupValue: function(json: IReportFlight) { return json.lAlt; } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.LastFlightLevel] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.LastFlightLevel, headingKey: 'ListLastFlightLevel', labelKey: 'LastFlightLevel', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.lAlt !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.flightLevel( json.lAlt, json.lAlt, VRS.AltitudeType.Barometric, json.fOnGnd, options.unitDisplayPreferences.getFlightLevelTransitionAltitude(), options.unitDisplayPreferences.getFlightLevelTransitionHeightUnit(), options.unitDisplayPreferences.getFlightLevelHeightUnit(), options.unitDisplayPreferences.getHeightUnit(), options.distinguishOnGround, options.showUnits, false ); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.LastHeading] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.LastHeading, headingKey: 'ListLastHeading', labelKey: 'LastHeading', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.lTrk !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.heading(json.lTrk, false, options.showUnits, false); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.LastLatitude] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.LastLatitude, headingKey: 'ListLastLatitude', labelKey: 'LastLatitude', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.lLat !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.latitude(json.lLat, options.showUnits); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.LastLongitude] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.LastLongitude, headingKey: 'ListLastLongitude', labelKey: 'LastLongitude', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.lLng !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.longitude(json.lLng, options.showUnits); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.LastOnGround] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.LastOnGround, headingKey: 'ListLastOnGround', labelKey: 'LastOnGround', hasValue: function(json: IReportFlight) { return json.lOnGnd !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.isOnGround(json.lOnGnd); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.LastSpeed] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.LastSpeed, headingKey: 'ListLastSpeed', labelKey: 'LastSpeed', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.lSpd !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.speed( json.lSpd, VRS.SpeedType.Ground, options.unitDisplayPreferences.getSpeedUnit(), options.showUnits, false ); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.LastSquawk] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.LastSquawk, headingKey: 'ListLastSquawk', labelKey: 'LastSquawk', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.lSqk !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.squawk(json.lSqk); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.LastVerticalSpeed] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.LastVerticalSpeed, headingKey: 'ListLastVerticalSpeed', labelKey: 'LastVerticalSpeed', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.lVsi !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.verticalSpeed(json.lVsi, json.fOnGnd, AltitudeType.Barometric, options.unitDisplayPreferences.getHeightUnit(), options.unitDisplayPreferences.getShowVerticalSpeedPerSecond(), options.showUnits); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.PositionsOnMap] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.PositionsOnMap, surfaces: VRS.ReportSurface.DetailBody, headingKey: 'Map', labelKey: 'Map', hasValue: function(json: IReportFlight) { return !!json.fLat || !!json.fLng || !!json.lLat || !!json.lLng; }, suppressLabelCallback: function() { return true; }, createWidget: function(element: JQuery, surface: ReportSurfaceBitFlags, options: ReportRender_Options) { if(surface === VRS.ReportSurface.DetailBody && !VRS.jQueryUIHelper.getReportMapPlugin(element)) { element.vrsReportMap(VRS.jQueryUIHelper.getReportMapOptions({ plotterOptions: options.plotterOptions, unitDisplayPreferences: options.unitDisplayPreferences, elementClasses: 'aircraftPosnMap' })); } }, destroyWidget: function(element: JQuery, surface: ReportSurfaceBitFlags) { var reportMap = VRS.jQueryUIHelper.getReportMapPlugin(element); if(surface === VRS.ReportSurface.DetailBody && reportMap) { reportMap.destroy(); } }, renderWidget: function(element: JQuery, flight: IReportFlight, options: ReportRender_Options, surface: ReportSurfaceBitFlags) { var reportMap = VRS.jQueryUIHelper.getReportMapPlugin(element); if(surface === VRS.ReportSurface.DetailBody && reportMap) { reportMap.showFlight(flight); } } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.RouteShort] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.RouteShort, headingKey: 'ListRoute', labelKey: 'RouteShort', hasValue: function(json: IReportFlight) { return !!json.route.from; }, contentCallback: function(json: IReportFlight) { return VRS.format.reportRouteShort(json.call, json.route, true, false); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.RouteFull] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.RouteFull, surfaces: VRS.ReportSurface.DetailBody, headingKey: 'ListRoute', labelKey: 'Route', isMultiLine: true, hasValue: function(json: IReportFlight) { return !!json.route.from; }, renderCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.reportRouteFull(json.call, json.route); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.RowNumber] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.RowNumber, headingKey: 'ListRowNumber', labelKey: 'RowNumber', surfaces: VRS.ReportSurface.List, hasValue: function(json: IReportFlight) { return true; }, contentCallback: function(json: IReportFlight) { return VRS.stringUtility.format('{0:N0}', json.row); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.Speed] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.Speed, headingKey: 'ListSpeed', labelKey: 'Speed', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.fSpd !== undefined || json.lSpd !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.speedFromTo(json.fSpd, json.lSpd, options.unitDisplayPreferences.getSpeedUnit(), options.showUnits); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.Squawk] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.Squawk, headingKey: 'ListSquawk', labelKey: 'Squawk', alignment: VRS.Alignment.Right, hasValue: function(json: IReportFlight) { return json.fSqk !== undefined || json.lSqk !== undefined; }, contentCallback: function(json: IReportFlight) { return VRS.format.squawkFromTo(json.fSqk, json.lSqk); } }); VRS.reportPropertyHandlers[VRS.ReportFlightProperty.StartTime] = new VRS.ReportPropertyHandler({ property: VRS.ReportFlightProperty.StartTime, headingKey: 'ListStartTime', labelKey: 'StartTime', hasValue: function(json: IReportFlight) { return json.start !== undefined; }, contentCallback: function(json: IReportFlight, options: ReportRender_Options) { return VRS.format.startDateTime(json.start, false, options.justShowStartTime); }, sortColumn: VRS.ReportSortColumn.Date, groupValue: function(json: IReportFlight) { return json.start ? Globalize.format(json.start, 'dddd d MMM yyyy') : null; } }); VRS.reportPropertyHandlers[VRS.ReportAircraftProperty.UserTag] = new VRS.ReportPropertyHandler({ property: VRS.ReportAircraftProperty.UserTag, headingKey: 'ListUserTag', labelKey: 'UserTag', hasValue: function(json: IReportAircraft) { return !!json.tag; }, contentCallback: function(json: IReportAircraft) { return VRS.format.userTag(json.tag); } }); /** * The settings that are passed to ReportPropertyHandlerHelper.addReportPropertyListOptionsToPane. */ export interface ReportPropertyHandlerHelper_AddPropertyToPaneSettings { /** * The pane to add the field to. */ pane: OptionPane; /** * The VRS.ReportSurface to show properties for. The user will be able to select any property that can be rendered to this surface. */ surface: ReportSurfaceBitFlags; /** * The index into VRS.$$ for the field's label. */ fieldLabel: string; /** * A method that returns a list of VRS.ReportProperty strings representing the properties selected by the user. */ getList: () => ReportAircraftOrFlightPropertyEnum[]; /** * A method that takes a list of VRS.ReportProperty strings selected by the user and copies them to the object being configured. */ setList: (list: ReportAircraftOrFlightPropertyEnum[]) => void; /** * A method that can save the state of the object being configured. */ saveState: () => void; } /** * A class that can perform routine ReportPropertyHandler tasks. */ export class ReportPropertyHandlerHelper { /** * Removes invalid report properties from a list, usually called as part of loading a previous session's state. */ buildValidReportPropertiesList(reportPropertyList: ReportAircraftOrFlightPropertyEnum[], surfaces: ReportSurfaceBitFlags[], maximumProperties?: number) : (ReportAircraftPropertyEnum | ReportFlightPropertyEnum)[] { maximumProperties = maximumProperties === undefined ? -1 : maximumProperties; surfaces = surfaces || []; if(surfaces.length === 0) { for(var surfaceName in VRS.ReportSurface) { surfaces.push(VRS.ReportSurface[surfaceName]); } } var countSurfaces = surfaces.length; var validProperties = []; $.each(reportPropertyList, function(idx, property) { if(maximumProperties === -1 || validProperties.length <= maximumProperties) { var handler = VRS.reportPropertyHandlers[property]; if(handler) { var surfaceSupported = false; for(var i = 0;i < countSurfaces;++i) { surfaceSupported = handler.isSurfaceSupported(surfaces[i]); if(surfaceSupported) break; } if(surfaceSupported) validProperties.push(property); } } }); return validProperties; } /** * Adds an orderedSubset field to an options pane that allows the user to configure a list of VRS.ReportProperty strings. */ addReportPropertyListOptionsToPane(settings: ReportPropertyHandlerHelper_AddPropertyToPaneSettings) : OptionFieldOrderedSubset { var pane = settings.pane; var surface = settings.surface; var fieldLabel = settings.fieldLabel; var getList = settings.getList; var setList = settings.setList; var saveState = settings.saveState; var values: ValueText[] = []; for(var property in VRS.reportPropertyHandlers) { var handler = VRS.reportPropertyHandlers[property]; if(!handler || !handler.isSurfaceSupported(surface)) continue; values.push(new VRS.ValueText({ value: handler.property, textKey: handler.optionsLabelKey })); } values.sort(function(lhs, rhs) { var lhsText = lhs.getText(); var rhsText = rhs.getText(); return lhsText.localeCompare(rhsText); }); var field = new VRS.OptionFieldOrderedSubset({ name: 'renderProperties', controlType: VRS.optionControlTypes.orderedSubset, labelKey: fieldLabel, getValue: getList, setValue: setList, saveState: saveState, values: values }); pane.addField(field); return field; } /** * Returns the VRS.ReportPropertyHandler that declares itself as the handler for the sort column passed across. */ findPropertyHandlerForSortColumn(sortColumn: ReportSortColumnEnum) : ReportPropertyHandler { var result: ReportPropertyHandler = null; if(sortColumn !== VRS.ReportSortColumn.None) { for(var property in VRS.reportPropertyHandlers) { var handler = VRS.reportPropertyHandlers[property]; if(handler.sortColumn && handler.sortColumn === sortColumn) { result = handler; break; } } } return result; } } /* * Pre-builts */ export var reportPropertyHandlerHelper = new VRS.ReportPropertyHandlerHelper(); }
the_stack
/// <reference types="cheerio" /> import { ReactElement, Component, AllHTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes, } from 'react'; export type HTMLAttributes = ReactHTMLAttributes<{}> & ReactSVGAttributes<{}>; export class ElementClass extends Component<any, any> {} /* These are purposefully stripped down versions of React.ComponentClass and React.StatelessComponent. * The optional static properties on them break overload ordering for wrapper methods if they're not * all specified in the implementation. TS chooses the EnzymePropSelector overload and loses the generics */ export interface ComponentClass<Props> { new (props: Props, context?: any): Component<Props>; } export type StatelessComponent<Props> = (props: Props, context?: any) => JSX.Element | null; export type ComponentType<Props> = ComponentClass<Props> | StatelessComponent<Props>; /** * Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the * following three categories: * * 1. A Valid CSS Selector * 2. A React Component Constructor * 3. A React Component's displayName * 4. A React Stateless component * 5. A React component property map */ export interface EnzymePropSelector { [key: string]: any; } export type EnzymeSelector = string | StatelessComponent<any> | ComponentClass<any> | EnzymePropSelector; export type Intercepter<T> = (intercepter: T) => void; export interface CommonWrapper<P = {}, S = {}, C = Component<P, S>> { /** * Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true. */ filterWhere(predicate: (wrapper: this) => boolean): this; /** * Returns whether or not the current wrapper has a node anywhere in it's render tree that looks like the one passed in. */ contains(node: ReactElement | ReactElement[] | string): boolean; /** * Returns whether or not a given react element exists in the shallow render tree. */ containsMatchingElement(node: ReactElement | ReactElement[]): boolean; /** * Returns whether or not all the given react elements exists in the shallow render tree */ containsAllMatchingElements(nodes: ReactElement[] | ReactElement[][]): boolean; /** * Returns whether or not one of the given react elements exists in the shallow render tree. */ containsAnyMatchingElements(nodes: ReactElement[] | ReactElement[][]): boolean; /** * Returns whether or not the current render tree is equal to the given node, based on the expected value. */ equals(node: ReactElement): boolean; /** * Returns whether or not a given react element matches the shallow render tree. */ matchesElement(node: ReactElement): boolean; /** * Returns whether or not the current node has a className prop including the passed in class name. */ hasClass(className: string | RegExp): boolean; /** * Invokes a function prop. * @param invokePropName The function prop to call. * @param ...args The argments to the invokePropName function * @returns The value of the function. */ invoke< K extends NonNullable< { [K in keyof P]: P[K] extends ((...arg: any[]) => void) | undefined ? K : never; }[keyof P] > >( invokePropName: K ): P[K]; /** * Returns whether or not the current node matches a provided selector. */ is(selector: EnzymeSelector): boolean; /** * Returns whether or not the current node is empty. * @deprecated Use .exists() instead. */ isEmpty(): boolean; /** * Returns whether or not the current node exists. */ exists(selector?: EnzymeSelector): boolean; /** * Returns a new wrapper with only the nodes of the current wrapper that don't match the provided selector. * This method is effectively the negation or inverse of filter. */ not(selector: EnzymeSelector): this; /** * Returns a string of the rendered text of the current render tree. This function should be looked at with * skepticism if being used to test what the actual HTML output of the component will be. If that is what you * would like to test, use enzyme's render function instead. * * Note: can only be called on a wrapper of a single node. */ text(): string; /** * Returns a string of the rendered HTML markup of the current render tree. * * Note: can only be called on a wrapper of a single node. */ html(): string; /** * Returns the node at a given index of the current wrapper. */ get(index: number): ReactElement; /** * Returns the wrapper's underlying node. */ getNode(): ReactElement; /** * Returns the wrapper's underlying nodes. */ getNodes(): ReactElement[]; /** * Returns the wrapper's underlying node. */ getElement(): ReactElement; /** * Returns the wrapper's underlying node. */ getElements(): ReactElement[]; /** * Returns the outer most DOMComponent of the current wrapper. */ getDOMNode<T extends Element = Element>(): T; /** * Returns a wrapper around the node at a given index of the current wrapper. */ at(index: number): this; /** * Reduce the set of matched nodes to the first in the set. */ first(): this; /** * Reduce the set of matched nodes to the last in the set. */ last(): this; /** * Returns a new wrapper with a subset of the nodes of the original wrapper, according to the rules of `Array#slice`. */ slice(begin?: number, end?: number): this; /** * Taps into the wrapper method chain. Helpful for debugging. */ tap(intercepter: Intercepter<this>): this; /** * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. */ state(): S; state<K extends keyof S>(key: K): S[K]; state<T>(key: string): T; /** * Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. */ context(): any; context<T>(key: string): T; /** * Returns the props hash for the current node of the wrapper. * * NOTE: can only be called on a wrapper of a single node. */ props(): P; /** * Returns the prop value for the node of the current wrapper with the provided key. * * NOTE: can only be called on a wrapper of a single node. */ prop<K extends keyof P>(key: K): P[K]; prop<T>(key: string): T; /** * Returns the key value for the node of the current wrapper. * NOTE: can only be called on a wrapper of a single node. */ key(): string; /** * Simulate events. * Returns itself. * @param args? */ simulate(event: string, ...args: any[]): this; /** * Used to simulate throwing a rendering error. Pass an error to throw. * Returns itself. * @param error */ simulateError(error: any): this; /** * A method to invoke setState() on the root component instance similar to how you might in the definition of * the component, and re-renders. This method is useful for testing your component in hard to achieve states, * however should be used sparingly. If possible, you should utilize your component's external API in order to * get it into whatever state you want to test, in order to be as accurate of a test as possible. This is not * always practical, however. * Returns itself. * * NOTE: can only be called on a wrapper instance that is also the root instance. */ setState<K extends keyof S>(state: Pick<S, K>, callback?: () => void): this; /** * A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test * how the component behaves over time with changing props. Calling this, for instance, will call the * componentWillReceiveProps lifecycle method. * * Similar to setState, this method accepts a props object and will merge it in with the already existing props. * Returns itself. * * NOTE: can only be called on a wrapper instance that is also the root instance. */ setProps<K extends keyof P>(props: Pick<P, K>, callback?: () => void): this; /** * A method that sets the context of the root component, and re-renders. Useful for when you are wanting to * test how the component behaves over time with changing contexts. * Returns itself. * * NOTE: can only be called on a wrapper instance that is also the root instance. */ setContext(context: any): this; /** * Gets the instance of the component being rendered as the root node passed into shallow(). * * NOTE: can only be called on a wrapper instance that is also the root instance. */ instance(): C; /** * Forces a re-render. Useful to run before checking the render output if something external may be updating * the state of the component somewhere. * Returns itself. * * NOTE: can only be called on a wrapper instance that is also the root instance. */ update(): this; /** * Returns an html-like string of the wrapper for debugging purposes. Useful to print out to the console when * tests are not passing when you expect them to. */ debug(options?: { /** Whether props should be omitted in the resulting string. Props are included by default. */ ignoreProps?: boolean; /** Whether arrays and objects passed as props should be verbosely printed. */ verbose?: boolean; }): string; /** * Returns the name of the current node of the wrapper. */ name(): string; /** * Iterates through each node of the current wrapper and executes the provided function with a wrapper around * the corresponding node passed in as the first argument. * * Returns itself. * @param fn A callback to be run for every node in the collection. Should expect a ShallowWrapper as the first * argument, and will be run with a context of the original instance. */ forEach(fn: (wrapper: this, index: number) => any): this; /** * Maps the current array of nodes to another array. Each node is passed in as a ShallowWrapper to the map * function. * Returns an array of the returned values from the mapping function.. * @param fn A mapping function to be run for every node in the collection, the results of which will be mapped * to the returned array. Should expect a ShallowWrapper as the first argument, and will be run * with a context of the original instance. */ map<V>(fn: (wrapper: this, index: number) => V): V[]; /** * Applies the provided reducing function to every node in the wrapper to reduce to a single value. Each node * is passed in as a ShallowWrapper, and is processed from left to right. */ reduce<R>(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R; /** * Applies the provided reducing function to every node in the wrapper to reduce to a single value. * Each node is passed in as a ShallowWrapper, and is processed from right to left. */ reduceRight<R>(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R; /** * Returns whether or not any of the nodes in the wrapper match the provided selector. */ some(selector: EnzymeSelector): boolean; /** * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. */ someWhere(fn: (wrapper: this) => boolean): boolean; /** * Returns whether or not all of the nodes in the wrapper match the provided selector. */ every(selector: EnzymeSelector): boolean; /** * Returns whether or not all of the nodes in the wrapper pass the provided predicate function. */ everyWhere(fn: (wrapper: this) => boolean): boolean; /** * Returns true if renderer returned null */ isEmptyRender(): boolean; /** * Renders the component to static markup and returns a Cheerio wrapper around the result. */ render(): Cheerio; /** * Returns the type of the current node of this wrapper. If it's a composite component, this will be the * component constructor. If it's native DOM node, it will be a string of the tag name. * * Note: can only be called on a wrapper of a single node. */ type(): string | ComponentClass<P> | StatelessComponent<P>; length: number; } export type Parameters<T> = T extends (...args: infer A) => any ? A : never; // tslint:disable-next-line no-empty-interface export interface ShallowWrapper<P = {}, S = {}, C = Component> extends CommonWrapper<P, S, C> {} export class ShallowWrapper<P = {}, S = {}, C = Component> { constructor(nodes: JSX.Element[] | JSX.Element, root?: ShallowWrapper<any, any>, options?: ShallowRendererProps); shallow(options?: ShallowRendererProps): ShallowWrapper<P, S>; unmount(): this; /** * Find every node in the render tree that matches the provided selector. * @param selector The selector to match. */ find<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>; find<P2>(component: ComponentType<P2>): ShallowWrapper<P2, any>; find<C2 extends Component>( componentClass: ComponentClass<C2['props']>, ): ShallowWrapper<C2['props'], C2['state'], C2>; find(props: EnzymePropSelector): ShallowWrapper<any, any>; find(selector: string): ShallowWrapper<HTMLAttributes, any>; /** * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ filter<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>; filter<P2>(component: ComponentType<P2>): ShallowWrapper<P2, any>; filter(props: EnzymePropSelector | string): ShallowWrapper<P, S>; /** * Finds every node in the render tree that returns true for the provided predicate function. */ findWhere(predicate: (wrapper: ShallowWrapper<any, any>) => boolean): ShallowWrapper<any, any>; /** * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector * can be provided and it will filter the children by this selector. */ children<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>; children<P2>(component: ComponentType<P2>): ShallowWrapper<P2, any>; children(selector: string): ShallowWrapper<HTMLAttributes, any>; children(props?: EnzymePropSelector): ShallowWrapper<any, any>; /** * Returns a new wrapper with child at the specified index. */ childAt(index: number): ShallowWrapper<any, any>; childAt<P2, S2>(index: number): ShallowWrapper<P2, S2>; /** * Shallow render the one non-DOM child of the current wrapper, and return a wrapper around the result. * NOTE: can only be called on wrapper of a single non-DOM component element node. */ dive<C2 extends Component, P2 = C2['props'], S2 = C2['state']>( options?: ShallowRendererProps ): ShallowWrapper<P2, S2, C2>; dive<P2, S2>(options?: ShallowRendererProps): ShallowWrapper<P2, S2>; dive<P2, S2, C2>(options?: ShallowRendererProps): ShallowWrapper<P2, S2, C2>; /** * Strips out all the not host-nodes from the list of nodes * * This method is useful if you want to check for the presence of host nodes * (actually rendered HTML elements) ignoring the React nodes. */ hostNodes(): ShallowWrapper<HTMLAttributes>; /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. * * Note: can only be called on a wrapper of a single node. */ parents<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>; parents<P2>(component: ComponentType<P2>): ShallowWrapper<P2, any>; parents(selector: string): ShallowWrapper<HTMLAttributes, any>; parents(props?: EnzymePropSelector): ShallowWrapper<any, any>; /** * Returns a wrapper of the first element that matches the selector by traversing up through the current node's * ancestors in the tree, starting with itself. * * Note: can only be called on a wrapper of a single node. */ closest<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>; closest<P2>(component: ComponentType<P2>): ShallowWrapper<P2, any>; closest(props: EnzymePropSelector): ShallowWrapper<any, any>; closest(selector: string): ShallowWrapper<HTMLAttributes, any>; /** * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ShallowWrapper<any, any>; /** * Returns a wrapper of the node rendered by the provided render prop. */ renderProp<PropName extends keyof P>( prop: PropName ): (...params: Parameters<P[PropName]>) => ShallowWrapper<any, never>; /** * If a wrappingComponent was passed in options, * this methods returns a ShallowWrapper around the rendered wrappingComponent. * This ShallowWrapper can be used to update the wrappingComponent's props and state */ getWrappingComponent: () => ShallowWrapper; } // tslint:disable-next-line no-empty-interface export interface ReactWrapper<P = {}, S = {}, C = Component> extends CommonWrapper<P, S, C> {} export class ReactWrapper<P = {}, S = {}, C = Component> { constructor(nodes: JSX.Element | JSX.Element[], root?: ReactWrapper<any, any>, options?: MountRendererProps); unmount(): this; mount(): this; /** * Returns a wrapper of the node that matches the provided reference name. * * NOTE: can only be called on a wrapper instance that is also the root instance. */ ref(refName: string): ReactWrapper<any, any>; ref<P2, S2>(refName: string): ReactWrapper<P2, S2>; /** * Detaches the react tree from the DOM. Runs ReactDOM.unmountComponentAtNode() under the hood. * * This method will most commonly be used as a "cleanup" method if you decide to use the attachTo option in mount(node, options). * * The method is intentionally not "fluent" (in that it doesn't return this) because you should not be doing anything with this wrapper after this method is called. * * Using the attachTo is not generally recommended unless it is absolutely necessary to test something. * It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though. */ detach(): void; /** * Strips out all the not host-nodes from the list of nodes * * This method is useful if you want to check for the presence of host nodes * (actually rendered HTML elements) ignoring the React nodes. */ hostNodes(): ReactWrapper<HTMLAttributes>; /** * Find every node in the render tree that matches the provided selector. * @param selector The selector to match. */ find<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>; find<P2>(component: ComponentType<P2>): ReactWrapper<P2, any>; find<C2 extends Component>( componentClass: ComponentClass<C2['props']>, ): ReactWrapper<C2['props'], C2['state'], C2>; find(props: EnzymePropSelector): ReactWrapper<any, any>; find(selector: string): ReactWrapper<HTMLAttributes, any>; /** * Finds every node in the render tree that returns true for the provided predicate function. */ findWhere(predicate: (wrapper: ReactWrapper<any, any>) => boolean): ReactWrapper<any, any>; /** * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ filter<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>; filter<P2>(component: ComponentType<P2>): ReactWrapper<P2, any>; filter(props: EnzymePropSelector | string): ReactWrapper<P, S>; /** * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector * can be provided and it will filter the children by this selector. */ children<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>; children<P2>(component: ComponentType<P2>): ReactWrapper<P2, any>; children(selector: string): ReactWrapper<HTMLAttributes, any>; children(props?: EnzymePropSelector): ReactWrapper<any, any>; /** * Returns a new wrapper with child at the specified index. */ childAt(index: number): ReactWrapper<any, any>; childAt<P2, S2>(index: number): ReactWrapper<P2, S2>; /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. * * Note: can only be called on a wrapper of a single node. */ parents<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>; parents<P2>(component: ComponentType<P2>): ReactWrapper<P2, any>; parents(selector: string): ReactWrapper<HTMLAttributes, any>; parents(props?: EnzymePropSelector): ReactWrapper<any, any>; /** * Returns a wrapper of the first element that matches the selector by traversing up through the current node's * ancestors in the tree, starting with itself. * * Note: can only be called on a wrapper of a single node. */ closest<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>; closest<P2>(component: ComponentType<P2>): ReactWrapper<P2, any>; closest(props: EnzymePropSelector): ReactWrapper<any, any>; closest(selector: string): ReactWrapper<HTMLAttributes, any>; /** * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ReactWrapper<any, any>; /** * If a wrappingComponent was passed in options, * this methods returns a ReactWrapper around the rendered wrappingComponent. * This ReactWrapper can be used to update the wrappingComponent's props and state */ getWrappingComponent: () => ReactWrapper; } export interface Lifecycles { componentDidUpdate?: { onSetState: boolean; prevContext: boolean; }; getDerivedStateFromProps?: { hasShouldComponentUpdateBug: boolean } | boolean; getChildContext?: { calledByRenderer: boolean; [key: string]: any; }; setState?: any; // TODO Maybe some life cycle are missing [lifecycleName: string]: any; } export interface ShallowRendererProps { // See https://github.com/airbnb/enzyme/blob/enzyme@3.10.0/docs/api/shallow.md#arguments /** * If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after * setProps and setContext. Default to false. */ disableLifecycleMethods?: boolean; /** * Enable experimental support for full react lifecycle methods */ lifecycleExperimental?: boolean; /** * Context to be passed into the component */ context?: any; /** * The legacy enableComponentDidUpdateOnSetState option should be matched by * `lifecycles: { componentDidUpdate: { onSetState: true } }`, for compatibility */ enableComponentDidUpdateOnSetState?: boolean; /** * the legacy supportPrevContextArgumentOfComponentDidUpdate option should be matched by * `lifecycles: { componentDidUpdate: { prevContext: true } }`, for compatibility */ supportPrevContextArgumentOfComponentDidUpdate?: boolean; lifecycles?: Lifecycles; /** * A component that will render as a parent of the node. * It can be used to provide context to the `node`, among other things. * See the [getWrappingComponent() docs](https://airbnb.io/enzyme/docs/api/ShallowWrapper/getWrappingComponent.html) for an example. * **Note**: `wrappingComponent` must render its children. */ wrappingComponent?: ComponentType<any>; /** * Initial props to pass to the `wrappingComponent` if it is specified. */ wrappingComponentProps?: {}; /** * If set to true, when rendering Suspense enzyme will replace all the lazy components in children * with fallback element prop. Otherwise it won't handle fallback of lazy component. * Default to true. Note: not supported in React < 16.6. */ suspenseFallback?: boolean; adapter?: EnzymeAdapter; /* TODO what are these doing??? */ attachTo?: any; hydrateIn?: any; PROVIDER_VALUES?: any; } export interface MountRendererProps { /** * Context to be passed into the component */ context?: {}; /** * DOM Element to attach the component to */ attachTo?: HTMLElement | null; /** * Merged contextTypes for all children of the wrapper */ childContextTypes?: {}; /** * A component that will render as a parent of the node. * It can be used to provide context to the `node`, among other things. * See the [getWrappingComponent() docs](https://airbnb.io/enzyme/docs/api/ShallowWrapper/getWrappingComponent.html) for an example. * **Note**: `wrappingComponent` must render its children. */ wrappingComponent?: ComponentType<any>; /** * Initial props to pass to the `wrappingComponent` if it is specified. */ wrappingComponentProps?: {}; } /** * Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that * your tests aren't indirectly asserting on behavior of child components. */ export function shallow<C extends Component, P = C['props'], S = C['state']>( node: ReactElement<P>, options?: ShallowRendererProps ): ShallowWrapper<P, S, C>; export function shallow<P>(node: ReactElement<P>, options?: ShallowRendererProps): ShallowWrapper<P, any>; export function shallow<P, S>(node: ReactElement<P>, options?: ShallowRendererProps): ShallowWrapper<P, S>; /** * Mounts and renders a react component into the document and provides a testing wrapper around it. */ export function mount<C extends Component, P = C['props'], S = C['state']>( node: ReactElement<P>, options?: MountRendererProps ): ReactWrapper<P, S, C>; export function mount<P>(node: ReactElement<P>, options?: MountRendererProps): ReactWrapper<P, any>; export function mount<P, S>(node: ReactElement<P>, options?: MountRendererProps): ReactWrapper<P, S>; /** * Render react components to static HTML and analyze the resulting HTML structure. */ export function render<P, S>(node: ReactElement<P>, options?: any): Cheerio; // See https://github.com/airbnb/enzyme/blob/v3.10.0/packages/enzyme/src/EnzymeAdapter.js export class EnzymeAdapter { wrapWithWrappingComponent?: (node: ReactElement, options?: ShallowRendererProps) => any; } /** * Configure enzyme to use the correct adapter for the react version * This is enabling the Enzyme configuration with adapters in TS */ export function configure(options: { adapter: EnzymeAdapter; // See https://github.com/airbnb/enzyme/blob/enzyme@3.10.0/docs/guides/migration-from-2-to-3.md#lifecycle-methods // Actually, `{adapter:} & Pick<ShallowRendererProps,"disableLifecycleMethods">` is more precise. However, // in that case jsdoc won't be shown /** * If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after * setProps and setContext. Default to false. */ disableLifecycleMethods?: boolean; }): void;
the_stack
import path from 'path'; import url from 'url'; import glob from 'glob-promise'; import chalk from 'chalk'; import { promises as fs, existsSync } from 'fs'; import { launch, Browser, Page } from 'puppeteer'; import PromisePool from 'es6-promise-pool'; import resemble from 'resemblejs'; import { Spec, SpecResult, SpecDefinition, SpecStep } from './types'; import { getReportHtml } from './reporting'; import { wait, getElement, addErrorMessage, saveErrorFile } from './utils'; const defaultSpecPath = '/example.php'; const defaultSelector = '.ag-root-wrapper'; const exampleBasePath = '/example-runner/'; const maxParallelPageLoads = 8; const failedTestsFile = 'tmp-failed-tests.txt'; const buildUrlQuery = (base: string, params: object) => { Object.entries(params).forEach(([key, value]) => { if (typeof value !== 'undefined') { const separator = base.includes('?') ? '&' : '?'; base += separator + encodeURIComponent(key) + '=' + encodeURIComponent(value); } }); return base; }; const createSpecFromDefinition = (definition: SpecDefinition): Spec => { let name: string; if (definition.name) { name = definition.name; } else if (definition.exampleSection) { name = `${definition.exampleSection}-${definition.exampleId}`; } else { throw new Error( `Spec definitions require a name or an example section: ${JSON.stringify(definition)}` ); } return { ...definition, name, steps: definition.steps || [ { name: 'default' } ], urlParams: definition.urlParams || {}, defaultViewport: definition.defaultViewport || { width: 800, height: 600 }, withoutThemes: definition.withoutThemes || [] }; }; interface RunContext { browser: Browser; passesFilter: Filter; server: string; handler: (screenshot: Buffer, specName: string) => Promise<void>; } // this function runs in the browser so can't reference any other functions or vars in this file // arguments are passed in by page.evaluateOnNewDocument const initInBrowser = (theme: string) => { try { if (document.readyState === 'complete') { throw new Error('This code is supposed to be run before ag-grid loads'); } const setTheme = () => { const themeElements = document.querySelectorAll( '[class^="ag-theme-"], [class*=" ag-theme-"]' ); themeElements.forEach(el => { el.className = el.className.replace(/ag-theme-\w+/g, theme); }); if (document.head) { const style = document.createElement('style'); style.innerHTML = // hide text cursor because it blinks, so screenshots vary based on timing ` input, textarea { caret-color: transparent !important; } ` + // disable all transitions because they mess up text rendering ` * { transition: none !important; } ` + // disable subpixel antialiasing because it causes variations between monitors ` * { -webkit-font-smoothing: antialiased; !important; }`; document.head.appendChild(style); } }; setTheme(); document.addEventListener('DOMContentLoaded', setTheme); // override Math.random with a PRNG so that examples that use random data don't // vary between screenshots // Uses the Park-Miller PRNG http://www.firstpr.com.au/dsp/rand31/ let seed = 728364; const limit = 2147483647; Math.random = () => { return (seed = (seed * 16807) % limit) / limit; }; } catch (e) { (window as any).initInBrowserError = e.stack || e.message; } }; const getTestCaseName = (spec: Spec, step: SpecStep) => `${spec.name}-${step.name}`; const getTestCaseImagePath = (folder: string, testCaseName: string) => path.join(folder, `${testCaseName}.png`); export const runSpec = async (spec: Spec, context: RunContext) => { let page: Page | null = null; try { let path = spec.path; if (spec.exampleSection || spec.exampleId) { if (path) { throw new Error(`Spec ${spec.name} provides both a path and an example.`); } const type = spec.exampleType || 'generated'; path = buildUrlQuery(exampleBasePath, { section: `javascript-grid-${spec.exampleSection}`, example: spec.exampleId, generated: type === 'generated' ? 1 : undefined, enterprise: !spec.community, grid: JSON.stringify({ height: '100%', width: '100%', enterprise: spec.community ? undefined : 1 }) }); } if (!path) { path = defaultSpecPath; } if (spec.urlParams) { path = buildUrlQuery(path, spec.urlParams); } page = await context.browser.newPage(); if (spec.urlParams.theme) { await page.evaluateOnNewDocument(initInBrowser, spec.urlParams.theme); } const pageUrl = url.resolve(context.server, path); await page.goto(pageUrl); const initInBrowserError = await page.evaluate(() => (window as any).initInBrowserError); if (initInBrowserError) { throw new Error('Error setting theme: ' + initInBrowserError); } let exampleHasLoaded = false; while (!exampleHasLoaded) { await wait(500); const content = await page.evaluate(() => document.body.textContent); exampleHasLoaded = content != null && !content.includes('Loading...'); } const selector = spec.selector || defaultSelector; const wrapper = await getElement(page, selector); for (let step of spec.steps) { const viewport = step.viewport || spec.defaultViewport; await page.setViewport(viewport); if (step.prepare) { await step.prepare(page); } const testCaseName = getTestCaseName(spec, step); if (context.passesFilter(testCaseName)) { // let CSS animations stabilise before taking screenshot await wait(500); const screenshotElement = step.selector ? await getElement(page, step.selector) : wrapper; const screenshot = await screenshotElement.screenshot({ encoding: 'binary' }); await context.handler(screenshot, testCaseName); } } } catch (e) { addErrorMessage(e, `Error in spec ${spec.name}`); if (page) { const message = await saveErrorFile(page); addErrorMessage(e, message); } throw e; } }; export const runSpecs = async (specs: Spec[], context: RunContext) => { let i = 0; const generateNextPromise = () => { const spec = specs[i++]; if (!spec) { return; } return runSpec(spec, context); }; await new PromisePool(generateNextPromise, maxParallelPageLoads).start(); }; const ensureEmptyFolder = async (folder: string, deleteImages: boolean) => { await fs.mkdir(folder, { recursive: true }); if (deleteImages) { const existing = await glob(path.join(folder, '*.png')); await Promise.all(existing.map(file => fs.unlink(file))); } }; interface ImageAnalysisResult { isSameDimensions: boolean; dimensionDifference: { width: number; height: number; }; rawMisMatchPercentage: number; misMatchPercentage: string; diffBounds: { top: number; left: number; bottom: number; right: number; }; analysisTime: number; getImageDataUrl: () => string; getBuffer: () => Buffer; } const getImageDifferences = async ( image1: Buffer, image2: Buffer ): Promise<ImageAnalysisResult> => { return new Promise((resolve, reject) => { (resemble as any).compare( image1, image2, { ignore: ['nothing', 'antialiasing'], largeImageThreshold: 2000 }, (err: any, result: ImageAnalysisResult) => { if (err) { reject(err); } else { resolve(result); } } ); }); }; const pngBufferToDataUri = (image: Buffer): string => 'data:image/png;base64,' + image.toString('base64'); export interface RunSuiteParams { specs: SpecDefinition[]; mode: 'compare' | 'update' | 'view'; folder: string; server: string; reportFile: string; filter: string; defaultThemes: string[]; onlyFailed: boolean; overwrite: boolean; clean: boolean; } type Filter = (testCaseName: string) => boolean; export const runSuite = async (params: RunSuiteParams) => { const log = console.error.bind(console); if (params.mode === 'update') { await ensureEmptyFolder(params.folder, params.clean); } let specsAlreadyCreated = 0; let filters: Filter[] = []; const nameMatchesFilter = (name: string) => !filters.find(f => !f(name)); if (params.filter) { const filterRegexp = new RegExp(params.filter); filters.push(name => filterRegexp.test(name)); } if (params.onlyFailed && existsSync(failedTestsFile)) { const failedLastRun = (await fs.readFile(failedTestsFile, 'utf8')).trim().split('\n'); log(chalk.yellow(`Limiting to ${failedLastRun.length} tests that failed last run.`)); filters.push(name => failedLastRun.includes(name)); } let specs: Spec[] = params.specs .map(createSpecFromDefinition) // generate rtl versions of provided specs .flatMap(spec => spec.autoRtl ? [ spec, { ...spec, name: `${spec.name}-rtl`, urlParams: { ...spec.urlParams, rtl: true } } ] : spec ) // generate alternate theme versions of provided specs .flatMap(spec => params.defaultThemes .filter(theme => !spec.withoutThemes.includes(theme)) .map(theme => ({ ...spec, name: `${spec.name}-${theme}`, urlParams: { ...spec.urlParams, theme: `ag-theme-${theme}` } })) ) // apply provided filter .filter(spec => { return ( nameMatchesFilter(spec.name) || spec.steps.find(step => nameMatchesFilter(getTestCaseName(spec, step))) ); }); if (params.mode === 'update' && !params.overwrite) { // skip specs where the images are already present specs = specs.filter(spec => { const testCaseNames = spec.steps.map(step => getTestCaseName(spec, step)); const imagePaths = testCaseNames.map(name => getTestCaseImagePath(params.folder, name)); const anyStepsMissingImage = !!imagePaths.find(path => !existsSync(path)); if (!anyStepsMissingImage) { ++specsAlreadyCreated; } return anyStepsMissingImage; }); } if (specsAlreadyCreated > 0) { log( chalk.rgb(255, 128, 0)( `${chalk.bold( 'NOTE:' )} skipping ${specsAlreadyCreated} specs that have already been generated. Pass --clean to generate all specs from scratch.` ) ); } const results: SpecResult[] = []; const writeReportFile = async (inProgress: boolean) => { const html = getReportHtml(results, inProgress); await fs.writeFile(params.reportFile, html); }; if (params.mode === 'view') { log('Generating view of existing images...'); for (const spec of specs) { for (const step of spec.steps) { const name = getTestCaseName(spec, step); if (nameMatchesFilter(name)) { const imageFile = getTestCaseImagePath(params.folder, name); const imageBuffer = await fs.readFile(imageFile); const dataUru = pngBufferToDataUri(imageBuffer); results.push({ type: 'view', name, originalUri: dataUru }); } } } await writeReportFile(false); log(`✨ report written to ${chalk.bold(path.relative('.', params.reportFile))}`); return; } log('Running suite...'); let reportIteration = -1; const reportGenerationInterval = 2500; const startTime = Date.now(); const browser = await launch({ args: ['--disable-gpu', '--font-render-hinting=none'] }); const totalMatchingTestCases = specs.reduce((acc, spec) => { const matchingCases = spec.steps.filter(step => nameMatchesFilter(getTestCaseName(spec, step)) ); return acc + matchingCases.length; }, 0); let testCasesRun = 0; let failedTestCases: string[] = []; await runSpecs(specs, { browser, passesFilter: nameMatchesFilter, server: params.server, handler: async (screenshot, testCaseName) => { ++testCasesRun; const file = getTestCaseImagePath(params.folder, testCaseName); if (params.mode === 'update') { await fs.writeFile(file, screenshot); process.stdout.clearLine(0); process.stdout.cursorTo(0); process.stdout.write( `🙌 generating: ${testCasesRun} of ${totalMatchingTestCases}` ); } else { const oldData = await fs.readFile(file); const result = await getImageDifferences(oldData, screenshot); const differenceUri = result.rawMisMatchPercentage > 0 ? result.getImageDataUrl() : null; results.push({ type: 'test', name: testCaseName, differenceUri, newUri: pngBufferToDataUri(screenshot), originalUri: pngBufferToDataUri(oldData), area: result.diffBounds }); process.stdout.clearLine(0); process.stdout.cursorTo(0); if (differenceUri) { log( `${chalk.red.bold(`✘ ${testCaseName}`)} - found difference, see report.html` ); failedTestCases.push(testCaseName); } process.stdout.write(`🙌 comparing: ${testCasesRun} of ${totalMatchingTestCases}`); } const thisReportIteration = Math.floor( (Date.now() - startTime) / reportGenerationInterval ); if (params.mode === 'compare' && reportIteration !== thisReportIteration) { reportIteration = thisReportIteration; await writeReportFile(true); } } }); await browser.close(); process.stdout.clearLine(0); process.stdout.cursorTo(0); if (testCasesRun === 0) { log(chalk.yellow('No test cases match filter')); } else if (params.mode === 'compare') { if (failedTestCases.length > 0) { log( chalk.red.bold( failedTestCases.length === 1 ? '1 FAILURE' : `${failedTestCases.length} FAILURES` ) ); await fs.writeFile(failedTestsFile, failedTestCases.join('\n')); } else { log(chalk.green.bold('ALL PASSED')); if (existsSync(failedTestsFile)) { await fs.unlink(failedTestsFile); } } await writeReportFile(false); log(`✨ report written to ${chalk.bold(path.relative('.', params.reportFile))}`); } else { process.stdout.clearLine(0); process.stdout.cursorTo(0); log(`✨ generated ${testCasesRun} images`); } };
the_stack
import type { Device, Cursor } from "spotify-types"; import type { Client } from "../Client"; import type { CamelCaseObjectKeys, CurrentPlayback, RecentlyPlayed } from "../Interface"; import { createCurrentPlayback, createCurrentlyPlaying, createDevice, createRecentlyPlayed } from "../structures/Player"; /** * A manager to perform actions which belongs to the spotify player web api. */ export class Player { /** * The spotify client. */ public readonly client!: Client; /** * The client which handles all the current user's player api endpoints. * All the methods in this class requires the user authorized token. * Few functions requires spotify premium. * * @param client The spotify api client. * @example const player = new Player(client); */ public constructor(client: Client) { Object.defineProperty(this, 'client', { value: client }); } /** * Get the current playback of the current user's player. * * @param additionalTypes A comma-separated list of item types that your client supports besides the default track type. Valid types are: track and episode. * @example const currentPlayback = await player.getCurrentPlayback(); */ public getCurrentPlayback(additionalTypes?: 'track' | 'episode'): Promise<CurrentPlayback | null> { return this.client.fetch(`/me/player`, { params: { additional_types: additionalTypes } }) .then(x => x ? createCurrentPlayback(this.client, x) : null); } /** * Get the current playing content of the current user's player. * * @param additionalTypes A comma-separated list of item types that your client supports besides the default track type. Valid types are: track and episode. * @example const currentPlayback = await player.getCurrentlyPlaying(); */ public getCurrentlyPlaying(additionalTypes?: 'track' | 'episode'): Promise<CurrentPlayback | null> { return this.client.fetch(`/me/player/currently-playing`, { params: { additional_types: additionalTypes } }) .then(x => x ? createCurrentlyPlaying(this.client, x) : null); } /** * Get the recently played data from the current user's player. * * @param options The before, after and limit query paramaeters. * @example const recentlyPlayed = await player.getRecentlyPlayed(); */ public getRecentlyPlayed(options: Partial<Cursor> & { limit?: number } = {}): Promise<RecentlyPlayed> { return this.client.fetch(`/me/player/recently-played`, { params: options }).then(x => createRecentlyPlayed(this.client, x)) } /** * Get the active devices which are logged into the current user's spotify account. * @example const devices = await player.getDevices(); */ public getDevices(): Promise<CamelCaseObjectKeys<Device>[]> { return this.client.fetch(`/me/player/devices`).then(x => x.devices.map(createDevice)) } /** * Transfer the playback to an another device. * This method requires a spotify premium account. * * @param deviceID The device id to be transferred. * @param play The playback state to set by default it is false. * @example await player.transferPlayback('deviceID'); */ public transferPlayback(deviceID: string, play = false): Promise<boolean> { return this.client.fetch(`/me/player`, { method: 'PUT', headers: { "Content-Type": "application/json" }, body: { device_ids: [deviceID], play } }).then(x => x != null); } /** * Play or resume the current user's playback. * This method requires a spotify premium account. * This methods uses the [/me/player/play] endpoint which does not has complete documentation. * * **Options for the function:** * - `deviceID` The id of the device this command is targeting. If not supplied, the user’s currently active device is the target. * - `contextURI` Not documented. * - `uris` Not documented. * - `offset` Not documented. * - `position` To seek to a position while playing. * * @param options The deviceID, contextURI, uris, offset and position parameter. * @example await player.play(); */ public play( options: { deviceID?: string, contextURI?: string, uris?: string[], offset?: number, position?: number } = {} ): Promise<boolean> { return this.client.fetch(`/me/player/play`, { method: 'PUT', headers: { "Content-Type": "application/json" }, params: { device_id: options.deviceID }, body: { context_uri: options.contextURI, uris: options.uris, offset: options.offset, position_ms: options.position } as any }).then(x => x != null); } /** * Pause the current user's playback. * This method requires a spotify premium account. * * @param deviceID The id of the device this command is targeting. If not supplied, the user’s currently active device is the target. * @example await player.pause(); */ async pause(deviceID?: string): Promise<boolean> { return this.client.fetch(`/me/player/pause`, { method: 'PUT', params: { device_id: deviceID } }).then(x => x != null); } /** * Skip to the next track in the current user's playback. * This method requires a spotify premium account. * * @param deviceID The id of the device this command is targeting. If not supplied, the user’s currently active device is the target. * @example await player.skip(); */ async skip(deviceID?: string): Promise<boolean> { return this.client.fetch(`/me/player/next`, { method: 'POST', params: { device_id: deviceID } }).then(x => x != null); } /** * Skip to the previous track in the current user's playback. * This method requires a spotify premium account. * * @param deviceID The id of the device this command is targeting. If not supplied, the user’s currently active device is the target. * @example await player.previous(); */ async previous(deviceID?: string): Promise<boolean> { return this.client.fetch(`/me/player/previous`, { method: 'POST', params: { device_id: deviceID } }).then(x => x != null); } /** * Seek to a paticular position in the current user's player. * This method requires a spotify premium account. * * @param position The position in milliseconds to seek to. Must be a positive number. Passing in a position that is greater than the length of the track will cause the player to start playing the next song. * @param deviceID The id of the device this command is targeting. If not supplied, the user’s currently active device is the target. * @example await player.seek(10000); */ async seek(position: number, deviceID?: string): Promise<boolean> { return this.client.fetch(`/me/player/seek`, { method: 'PUT', params: { position_ms: position, device_id: deviceID } }).then(x => x != null); } /** * Set the repeat mode for the user’s playback. * This method requires a spotify premium account. * * @param state State should be track, context or off. **track** will repeat the current track. **context** will repeat the current context. **off** will turn repeat off. * @param deviceID The id of the device this command is targeting. If not supplied, the user’s currently active device is the target. * @example await player.setRepeatState('off'); */ async setRepeatState(state: 'track' | 'context' | 'off', deviceID?: string): Promise<boolean> { return this.client.fetch(`/me/player/repeat`, { method: 'PUT', params: { device_id: deviceID, state } }).then(x => x != null); } /** * Toggle shuffle state for the current user's playback. * This method requires a spotify premium account. * * @param state The shuffle state to set. * @param deviceID The id of the device this command is targeting. If not supplied, the user’s currently active device is the target. * @example await player.setShuffleState(); */ async setShuffleState(state = true, deviceID?: string): Promise<boolean> { return this.client.fetch(`/me/player/shuffle`, { method: 'PUT', params: { device_id: deviceID, state } }).then(x => x != null); } /** * Set volume for the current user's player. * This method requires a spotify premium account. * * @param volume The volume to set. Must be a value from 0 to 100 inclusive. * @param deviceID The id of the device this command is targeting. If not supplied, the user’s currently active device is the target. * @example await player.setVolume(80); */ async setVolume(volume: number, deviceID?: string): Promise<boolean> { return this.client.fetch(`/me/player/volume`, { method: 'PUT', params: { volume_percent: volume, device_id: deviceID } }).then(x => x != null); } /** * Add an item to the current user's queue. * This method requires a spotify premium account. * * @param uri The uri of the track or the episode to add to the queue. * @param deviceID The id of the device this command is targeting. If not supplied, the user’s currently active device is the target. * @example await player.addItem('uri'); */ async addItem(uri: string, deviceID?: string): Promise<boolean> { return this.client.fetch(`/me/player/queue`, { method: 'POST', params: { device_id: deviceID, uri } }).then(x => x != null); } }
the_stack
import * as React from "react"; import { IModelApp, NotifyMessageDetails, OutputMessagePriority } from "@itwin/core-frontend"; import { DialogButtonDef, DialogButtonType, DialogItem, DialogItemValue, DialogLayoutDataProvider, DialogPropertyItem, DialogPropertySyncItem, PropertyChangeResult, PropertyChangeStatus, PropertyDescription, StandardContentLayouts, StandardTypeNames, WidgetState, } from "@itwin/appui-abstract"; import { ActionItemButton, CommandItemDef, ContentGroup, CoreTools, Frontstage, FrontstageProps, FrontstageProvider, GroupButton, ModalDialogManager, ModelessDialogManager, NavigationWidget, StagePanel, StagePanelState, ToolButton, ToolWidget, Widget, Zone, ZoneState, } from "@itwin/appui-react"; import { Direction, Toolbar } from "@itwin/appui-layout-react"; import { AppTools } from "../../tools/ToolSpecifications"; import { PopupTestDialog } from "../dialogs/PopupTest"; import { SampleModalDialog } from "../dialogs/SampleModalDialog"; import { SampleModelessDialog } from "../dialogs/SampleModelessDialog"; import { SpinnerTestDialog } from "../dialogs/SpinnerTestDialog"; import { TestModalDialog } from "../dialogs/TestModalDialog"; import { TestModalDialog2 } from "../dialogs/TestModalDialog2"; import { TestRadialMenu } from "../dialogs/TestRadialMenu"; import { TestReactSelectDialog } from "../dialogs/TestReactSelectDialog"; import { TestUiProvider } from "../dialogs/TestUiProviderDialog"; import { BreadcrumbDemoWidgetControl } from "../widgets/BreadcrumbDemoWidget"; import { NavigationTreeWidgetControl } from "../widgets/NavigationTreeWidget"; import { HorizontalPropertyGridWidgetControl, HorizontalPropertyGridWidgetControl2, VerticalPropertyGridWidgetControl, } from "../widgets/PropertyGridDemoWidget"; import { TableDemoWidgetControl } from "../widgets/TableDemoWidget"; import { TreeSelectionDemoWidgetControl } from "../widgets/TreeSelectionDemoWidget"; /* eslint-disable react/jsx-key, deprecation/deprecation */ class DynamicModalUiDataProvider extends DialogLayoutDataProvider { public currentPageIndex = 0; public numberOfPages = 2; public static userPropertyName = "username"; private static _getUserDescription = (): PropertyDescription => { return { name: DynamicModalUiDataProvider.userPropertyName, displayLabel: "User", typename: StandardTypeNames.String, }; }; private _userValue: DialogItemValue = { value: "unknown" }; private get user(): string { return this._userValue.value as string; } private set user(option: string) { this._userValue.value = option; } public static cityPropertyName = "city"; private static _getCityDescription = (): PropertyDescription => { return { name: DynamicModalUiDataProvider.cityPropertyName, displayLabel: "City", typename: StandardTypeNames.String, }; }; private _cityValue: DialogItemValue = { value: "unknown" }; private get city(): string { return this._cityValue.value as string; } private set city(option: string) { this._cityValue.value = option; } // called to apply a single property value change. public override applyUiPropertyChange = (updatedValue: DialogPropertySyncItem): void => { this.processChangesInUi([updatedValue]); }; /** Called by UI to inform data provider of changes. */ public override processChangesInUi(properties: DialogPropertyItem[]): PropertyChangeResult { if (properties.length > 0) { for (const prop of properties) { if (prop.propertyName === DynamicModalUiDataProvider.userPropertyName) { this.user = prop.value.value ? prop.value.value as string : ""; continue; } else if (prop.propertyName === DynamicModalUiDataProvider.cityPropertyName) { this.city = prop.value.value ? prop.value.value as string : ""; continue; } } } this.fireDialogButtonsReloadEvent(); return { status: PropertyChangeStatus.Success }; } /** Used Called by UI to request available properties when UI is manually created. */ public override supplyDialogItems(): DialogItem[] | undefined { const items: DialogItem[] = []; items.push({ value: this._userValue, property: DynamicModalUiDataProvider._getUserDescription(), editorPosition: { rowPriority: 1, columnIndex: 1 } }); if (this.currentPageIndex > 0) { items.push({ value: this._cityValue, property: DynamicModalUiDataProvider._getCityDescription(), editorPosition: { rowPriority: 2, columnIndex: 1 } }); } return items; } public handleNext = () => { if (this.currentPageIndex < this.numberOfPages) { this.currentPageIndex++; this.reloadDialogItems(); } }; public handlePrevious = () => { if (this.currentPageIndex > 0) { this.currentPageIndex--; this.reloadDialogItems(); } }; public override supplyButtonData(): DialogButtonDef[] | undefined { const buttons: DialogButtonDef[] = []; if (this.currentPageIndex > 0 && this.currentPageIndex < this.numberOfPages) buttons.push({ type: DialogButtonType.Previous, onClick: this.handlePrevious }); if (this.currentPageIndex < this.numberOfPages - 1) buttons.push({ type: DialogButtonType.Next, onClick: this.handleNext }); if (this.currentPageIndex === this.numberOfPages - 1) { buttons.push({ type: DialogButtonType.OK, onClick: () => { }, disabled: (this.user === "unknown" || this.city === "unknown") }); } buttons.push({ type: DialogButtonType.Cancel, onClick: () => { } }); return buttons; } } export class Frontstage4 extends FrontstageProvider { public get id(): string { return "Test4"; } public get frontstage(): React.ReactElement<FrontstageProps> { const myContentGroup: ContentGroup = new ContentGroup( { id: "CubeContent", layout: StandardContentLayouts.singleView, contents: [ { id: "navigationCube", classId: "CubeContent", }, ], }, ); return ( <Frontstage id={this.id} defaultTool={CoreTools.selectElementCommand} contentGroup={myContentGroup} defaultContentId="TestContent1" isInFooterMode={true} contentManipulationTools={ <Zone widgets={[ <Widget isFreeform={true} element={this.getToolWidget()} />, ]} /> } toolSettings={ <Zone widgets={[ <Widget isToolSettings={true} />, ]} /> } viewNavigationTools={ <Zone widgets={[ <Widget isFreeform={true} element={this.getNavigationWidget()} />, ]} /> } centerRight={ <Zone defaultState={ZoneState.Minimized} allowsMerging={false} widgets={[ <Widget iconSpec="icon-placeholder" labelKey="SampleApp:widgets.NavigationTree" control={NavigationTreeWidgetControl} />, <Widget iconSpec="icon-placeholder" labelKey="SampleApp:widgets.BreadcrumbDemo" control={BreadcrumbDemoWidgetControl} />, <Widget iconSpec="icon-placeholder" labelKey="SampleApp:widgets.TreeSelectionDemo" control={TreeSelectionDemoWidgetControl} />, ]} /> } rightPanel={<StagePanel defaultState={StagePanelState.Minimized} panelZones={{ start: { widgets: [ <Widget iconSpec="icon-placeholder" labelKey="SampleApp:widgets.NavigationTree" control={NavigationTreeWidgetControl} />, <Widget iconSpec="icon-placeholder" labelKey="SampleApp:widgets.BreadcrumbDemo" control={BreadcrumbDemoWidgetControl} />, <Widget iconSpec="icon-placeholder" labelKey="SampleApp:widgets.TreeSelectionDemo" control={TreeSelectionDemoWidgetControl} />, ], }, end: { widgets: [ <Widget id="VerticalPropertyGrid" defaultState={WidgetState.Hidden} iconSpec="icon-placeholder" labelKey="SampleApp:widgets.VerticalPropertyGrid" control={VerticalPropertyGridWidgetControl} />, <Widget defaultState={WidgetState.Open} iconSpec="icon-placeholder" labelKey="SampleApp:widgets.HorizontalPropertyGrid" control={HorizontalPropertyGridWidgetControl2} />, <Widget iconSpec="icon-placeholder" labelKey="SampleApp:widgets.TableDemo" control={TableDemoWidgetControl} />, ], }, }} />} statusBar={ <Zone widgets={[ <Widget isStatusBar={true} classId="SmallStatusBar" />, ]} /> } bottomRight={ <Zone defaultState={ZoneState.Open} allowsMerging={true} widgets={[ <Widget id="VerticalPropertyGrid" defaultState={WidgetState.Hidden} iconSpec="icon-placeholder" labelKey="SampleApp:widgets.VerticalPropertyGrid" control={VerticalPropertyGridWidgetControl} />, <Widget defaultState={WidgetState.Open} iconSpec="icon-placeholder" labelKey="SampleApp:widgets.HorizontalPropertyGrid" control={HorizontalPropertyGridWidgetControl} />, <Widget iconSpec="icon-placeholder" labelKey="SampleApp:widgets.TableDemo" control={TableDemoWidgetControl} />, ]} /> } /> ); } /** Define a ToolWidget with Buttons to display in the TopLeft zone. */ private getToolWidget(): React.ReactNode { const horizontalToolbar = <Toolbar expandsTo={Direction.Bottom} items={ <> <ToolButton toolId={AppTools.tool2.id} iconSpec={AppTools.tool2.iconSpec} labelKey={AppTools.tool2.label} execute={AppTools.tool2.execute} /> <GroupButton labelKey="SampleApp:buttons.toolGroup" iconSpec="icon-placeholder" items={[ AppTools.tool1, AppTools.tool2, AppTools.infoMessageCommand, AppTools.warningMessageCommand, AppTools.errorMessageCommand, AppTools.noIconMessageCommand, AppTools.item6, AppTools.item7, AppTools.item8]} direction={Direction.Bottom} itemsInColumn={5} /> </> } />; const verticalToolbar = <Toolbar expandsTo={Direction.Right} items={ <> <ToolButton toolId={AppTools.tool1.id} iconSpec={AppTools.tool1.iconSpec} labelKey={AppTools.tool1.label} execute={AppTools.tool1.execute} /> <ToolButton toolId={AppTools.tool2.id} iconSpec={AppTools.tool2.iconSpec} labelKey={AppTools.tool2.label} execute={AppTools.tool2.execute} /> <GroupButton labelKey="SampleApp:buttons.anotherGroup" iconSpec="icon-placeholder" items={[ AppTools.tool1, AppTools.tool2, AppTools.item3, AppTools.item4, AppTools.item5, AppTools.item6, AppTools.item7, AppTools.item8, ]} direction={Direction.Right} /> <ActionItemButton actionItem={AppTools.activityMessageItem} /> <ToolButton toolId={AppTools.addMessageCommand.commandId} iconSpec={AppTools.addMessageCommand.iconSpec} labelKey={AppTools.addMessageCommand.label} execute={AppTools.addMessageCommand.execute} /> </> } />; return ( <ToolWidget appButton={AppTools.backstageToggleCommand} horizontalToolbar={horizontalToolbar} verticalToolbar={verticalToolbar} /> ); } private modalDialog(): React.ReactNode { return ( <TestModalDialog opened={true} /> ); } private modalDialog2(): React.ReactNode { return ( <TestModalDialog2 opened={true} /> ); } private testPopup(): React.ReactNode { return ( <PopupTestDialog opened={true} /> ); } private radialMenu(): React.ReactNode { return ( <TestRadialMenu opened={true} onClose={this._closeModal} /> ); } private _closeModal = () => { ModalDialogManager.closeDialog(); }; private get _spinnerTestDialogItem() { const id = "spinners"; return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.spinnerTestDialog", execute: () => { ModelessDialogManager.openDialog(<SpinnerTestDialog opened={true} onClose={() => ModelessDialogManager.closeDialog(id)} />, id); }, }); } private get _sampleModelessDialogItem() { const dialogId = "sample"; return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.sampleModelessDialog", execute: () => { ModelessDialogManager.openDialog( <SampleModelessDialog opened={true} dialogId={dialogId} onClose={() => this._handleModelessClose(dialogId)} />, dialogId); }, }); } private _handleModelessClose = (dialogId: string) => { ModelessDialogManager.closeDialog(dialogId); IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, `Closed modeless dialog: ${dialogId}`)); }; private get _sampleModalDialogItem() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.sampleModalDialog", // eslint-disable-next-line no-console execute: () => { ModalDialogManager.openDialog( <SampleModalDialog opened={true} onResult={(result) => this._handleModalResult(result)} />); }, }); } private _handleModalResult(result: DialogButtonType) { ModalDialogManager.closeDialog(); IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, `Modal dialog result: ${result}`)); } private handleOpenUiProviderDialogModal = () => { IModelApp.uiAdmin.openDialog(new TestUiProvider(), "Test UiProvider", true, "TestUiProvider", { movable: true, width: "auto", }); }; private testReactSelectDialog(): React.ReactNode { return ( <TestReactSelectDialog opened={true} /> ); } private handleOpenDynamicModal = () => { IModelApp.uiAdmin.openDialog(new DynamicModalUiDataProvider(), "Dynamic Model", true, "SampleApp:DynamicModal", { movable: true, width: 280, minWidth: 280, }); }; /** Define a NavigationWidget with Buttons to display in the TopRight zone. */ private getNavigationWidget(): React.ReactNode { const horizontalToolbar = <Toolbar expandsTo={Direction.Bottom} items={ <> <ToolButton toolId={AppTools.item6.id} iconSpec={AppTools.item6.iconSpec} labelKey={AppTools.item6.label} /> <ToolButton toolId={AppTools.item5.id} iconSpec={AppTools.item5.iconSpec} labelKey={AppTools.item5.label} /> <ToolButton toolId="openDialog" label="open modal" iconSpec="icon-placeholder" execute={() => ModalDialogManager.openDialog(this.modalDialog())} /> <ToolButton toolId="openDialog2" label="open modal 2" iconSpec="icon-placeholder" execute={() => ModalDialogManager.openDialog(this.modalDialog2())} /> <ToolButton toolId="openDynamicModal" label="open dynamic modal" iconSpec="icon-tools" execute={this.handleOpenDynamicModal} /> <ToolButton toolId="openRadial" iconSpec="icon-placeholder" execute={() => ModalDialogManager.openDialog(this.radialMenu())} /> <ToolButton toolId="popupTest" iconSpec="icon-placeholder" execute={() => ModalDialogManager.openDialog(this.testPopup())} /> <ToolButton toolId="uiProviderModalTest" iconSpec="icon-placeholder" execute={this.handleOpenUiProviderDialogModal} /> <ToolButton toolId="reactSelectModalTest" iconSpec="icon-lightbulb" execute={() => ModalDialogManager.openDialog(this.testReactSelectDialog())} /> </> } />; const verticalToolbar = <Toolbar expandsTo={Direction.Left} items={ <> <ToolButton toolId={AppTools.item8.id} iconSpec={AppTools.item8.iconSpec} labelKey={AppTools.item8.label} /> <ToolButton toolId={AppTools.item7.id} iconSpec={AppTools.item7.iconSpec} labelKey={AppTools.item7.label} /> <GroupButton labelKey="SampleApp:buttons.toolGroup" iconSpec="icon-placeholder" items={[ AppTools.successMessageBoxCommand, AppTools.informationMessageBoxCommand, AppTools.questionMessageBoxCommand, AppTools.warningMessageBoxCommand, AppTools.errorMessageBoxCommand, AppTools.openMessageBoxCommand, AppTools.openMessageBoxCommand2, this._spinnerTestDialogItem, this._sampleModelessDialogItem, this._sampleModalDialogItem, ]} direction={Direction.Left} itemsInColumn={7} /> </> } />; return ( <NavigationWidget navigationAidId="CubeNavigationAid" horizontalToolbar={horizontalToolbar} verticalToolbar={verticalToolbar} /> ); } }
the_stack
declare module 'tls' { import * as net from 'net'; const CLIENT_RENEG_LIMIT: number; const CLIENT_RENEG_WINDOW: number; interface Certificate { /** * Country code. */ C: string; /** * Street. */ ST: string; /** * Locality. */ L: string; /** * Organization. */ O: string; /** * Organizational unit. */ OU: string; /** * Common name. */ CN: string; } interface PeerCertificate { subject: Certificate; issuer: Certificate; subjectaltname: string; infoAccess: NodeJS.Dict<string[]>; modulus: string; exponent: string; valid_from: string; valid_to: string; fingerprint: string; fingerprint256: string; ext_key_usage: string[]; serialNumber: string; raw: Buffer; } interface DetailedPeerCertificate extends PeerCertificate { issuerCertificate: DetailedPeerCertificate; } interface CipherNameAndProtocol { /** * The cipher name. */ name: string; /** * SSL/TLS protocol version. */ version: string; /** * IETF name for the cipher suite. */ standardName: string; } interface EphemeralKeyInfo { /** * The supported types are 'DH' and 'ECDH'. */ type: string; /** * The name property is available only when type is 'ECDH'. */ name?: string | undefined; /** * The size of parameter of an ephemeral key exchange. */ size: number; } interface KeyObject { /** * Private keys in PEM format. */ pem: string | Buffer; /** * Optional passphrase. */ passphrase?: string | undefined; } interface PxfObject { /** * PFX or PKCS12 encoded private key and certificate chain. */ buf: string | Buffer; /** * Optional passphrase. */ passphrase?: string | undefined; } interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { /** * If true the TLS socket will be instantiated in server-mode. * Defaults to false. */ isServer?: boolean | undefined; /** * An optional net.Server instance. */ server?: net.Server | undefined; /** * An optional Buffer instance containing a TLS session. */ session?: Buffer | undefined; /** * If true, specifies that the OCSP status request extension will be * added to the client hello and an 'OCSPResponse' event will be * emitted on the socket before establishing a secure communication */ requestOCSP?: boolean | undefined; } class TLSSocket extends net.Socket { /** * Construct a new tls.TLSSocket object from an existing TCP socket. */ constructor(socket: net.Socket, options?: TLSSocketOptions); /** * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. */ authorized: boolean; /** * The reason why the peer's certificate has not been verified. * This property becomes available only when tlsSocket.authorized === false. */ authorizationError: Error; /** * Static boolean value, always true. * May be used to distinguish TLS sockets from regular ones. */ encrypted: boolean; /** * String containing the selected ALPN protocol. * Before a handshake has completed, this value is always null. * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. */ alpnProtocol: string | false | null; /** * Returns an object representing the local certificate. The returned * object has some properties corresponding to the fields of the * certificate. * * See tls.TLSSocket.getPeerCertificate() for an example of the * certificate structure. * * If there is no local certificate, an empty object will be returned. * If the socket has been destroyed, null will be returned. */ getCertificate(): PeerCertificate | object | null; /** * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. * @returns Returns an object representing the cipher name * and the SSL/TLS protocol version of the current connection. */ getCipher(): CipherNameAndProtocol; /** * Returns an object representing the type, name, and size of parameter * of an ephemeral key exchange in Perfect Forward Secrecy on a client * connection. It returns an empty object when the key exchange is not * ephemeral. As this is only supported on a client socket; null is * returned if called on a server socket. The supported types are 'DH' * and 'ECDH'. The name property is available only when type is 'ECDH'. * * For example: { type: 'ECDH', name: 'prime256v1', size: 256 }. */ getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; /** * Returns the latest Finished message that has * been sent to the socket as part of a SSL/TLS handshake, or undefined * if no Finished message has been sent yet. * * As the Finished messages are message digests of the complete * handshake (with a total of 192 bits for TLS 1.0 and more for SSL * 3.0), they can be used for external authentication procedures when * the authentication provided by SSL/TLS is not desired or is not * enough. * * Corresponds to the SSL_get_finished routine in OpenSSL and may be * used to implement the tls-unique channel binding from RFC 5929. */ getFinished(): Buffer | undefined; /** * Returns an object representing the peer's certificate. * The returned object has some properties corresponding to the field of the certificate. * If detailed argument is true the full chain with issuer property will be returned, * if false only the top certificate without issuer property. * If the peer does not provide a certificate, it returns null or an empty object. * @param detailed - If true; the full chain with issuer property will be returned. * @returns An object representing the peer's certificate. */ getPeerCertificate(detailed: true): DetailedPeerCertificate; getPeerCertificate(detailed?: false): PeerCertificate; getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; /** * Returns the latest Finished message that is expected or has actually * been received from the socket as part of a SSL/TLS handshake, or * undefined if there is no Finished message so far. * * As the Finished messages are message digests of the complete * handshake (with a total of 192 bits for TLS 1.0 and more for SSL * 3.0), they can be used for external authentication procedures when * the authentication provided by SSL/TLS is not desired or is not * enough. * * Corresponds to the SSL_get_peer_finished routine in OpenSSL and may * be used to implement the tls-unique channel binding from RFC 5929. */ getPeerFinished(): Buffer | undefined; /** * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. * The value `null` will be returned for server sockets or disconnected client sockets. * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. * @returns negotiated SSL/TLS protocol version of the current connection */ getProtocol(): string | null; /** * Could be used to speed up handshake establishment when reconnecting to the server. * @returns ASN.1 encoded TLS session or undefined if none was negotiated. */ getSession(): Buffer | undefined; /** * Returns a list of signature algorithms shared between the server and * the client in the order of decreasing preference. */ getSharedSigalgs(): string[]; /** * NOTE: Works only with client TLS sockets. * Useful only for debugging, for session reuse provide session option to tls.connect(). * @returns TLS session ticket or undefined if none was negotiated. */ getTLSTicket(): Buffer | undefined; /** * Returns true if the session was reused, false otherwise. */ isSessionReused(): boolean; /** * Initiate TLS renegotiation process. * * NOTE: Can be used to request peer's certificate after the secure connection has been established. * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. * @param options - The options may contain the following fields: rejectUnauthorized, * requestCert (See tls.createServer() for details). * @param callback - callback(err) will be executed with null as err, once the renegotiation * is successfully completed. * @return `undefined` when socket is destroy, `false` if negotiaion can't be initiated. */ renegotiate(options: { rejectUnauthorized?: boolean | undefined, requestCert?: boolean | undefined }, callback: (err: Error | null) => void): undefined | boolean; /** * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by * the TLS layer until the entire fragment is received and its integrity is verified; * large fragments can span multiple roundtrips, and their processing can be delayed due to packet * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, * which may decrease overall server throughput. * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). * @returns Returns true on success, false otherwise. */ setMaxSendFragment(size: number): boolean; /** * Disables TLS renegotiation for this TLSSocket instance. Once called, * attempts to renegotiate will trigger an 'error' event on the * TLSSocket. */ disableRenegotiation(): void; /** * When enabled, TLS packet trace information is written to `stderr`. This can be * used to debug TLS connection problems. * * Note: The format of the output is identical to the output of `openssl s_client * -trace` or `openssl s_server -trace`. While it is produced by OpenSSL's * `SSL_trace()` function, the format is undocumented, can change without notice, * and should not be relied on. */ enableTrace(): void; /** * @param length number of bytes to retrieve from keying material * @param label an application specific label, typically this will be a value from the * [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). * @param context optionally provide a context. */ exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; addListener(event: "secureConnect", listener: () => void): this; addListener(event: "session", listener: (session: Buffer) => void): this; addListener(event: "keylog", listener: (line: Buffer) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "OCSPResponse", response: Buffer): boolean; emit(event: "secureConnect"): boolean; emit(event: "session", session: Buffer): boolean; emit(event: "keylog", line: Buffer): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "OCSPResponse", listener: (response: Buffer) => void): this; on(event: "secureConnect", listener: () => void): this; on(event: "session", listener: (session: Buffer) => void): this; on(event: "keylog", listener: (line: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "OCSPResponse", listener: (response: Buffer) => void): this; once(event: "secureConnect", listener: () => void): this; once(event: "session", listener: (session: Buffer) => void): this; once(event: "keylog", listener: (line: Buffer) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependListener(event: "secureConnect", listener: () => void): this; prependListener(event: "session", listener: (session: Buffer) => void): this; prependListener(event: "keylog", listener: (line: Buffer) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependOnceListener(event: "secureConnect", listener: () => void): this; prependOnceListener(event: "session", listener: (session: Buffer) => void): this; prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; } interface CommonConnectionOptions { /** * An optional TLS context object from tls.createSecureContext() */ secureContext?: SecureContext | undefined; /** * When enabled, TLS packet trace information is written to `stderr`. This can be * used to debug TLS connection problems. * @default false */ enableTrace?: boolean | undefined; /** * If true the server will request a certificate from clients that * connect and attempt to verify that certificate. Defaults to * false. */ requestCert?: boolean | undefined; /** * An array of strings or a Buffer naming possible ALPN protocols. * (Protocols should be ordered by their priority.) */ ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; /** * SNICallback(servername, cb) <Function> A function that will be * called if the client supports SNI TLS extension. Two arguments * will be passed when called: servername and cb. SNICallback should * invoke cb(null, ctx), where ctx is a SecureContext instance. * (tls.createSecureContext(...) can be used to get a proper * SecureContext.) If SNICallback wasn't provided the default callback * with high-level API will be used (see below). */ SNICallback?: ((servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void) | undefined; /** * If true the server will reject any connection which is not * authorized with the list of supplied CAs. This option only has an * effect if requestCert is true. * @default true */ rejectUnauthorized?: boolean | undefined; } interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { /** * Abort the connection if the SSL/TLS handshake does not finish in the * specified number of milliseconds. A 'tlsClientError' is emitted on * the tls.Server object whenever a handshake times out. Default: * 120000 (120 seconds). */ handshakeTimeout?: number | undefined; /** * The number of seconds after which a TLS session created by the * server will no longer be resumable. See Session Resumption for more * information. Default: 300. */ sessionTimeout?: number | undefined; /** * 48-bytes of cryptographically strong pseudo-random data. */ ticketKeys?: Buffer | undefined; /** * * @param socket * @param identity identity parameter sent from the client. * @return pre-shared key that must either be * a buffer or `null` to stop the negotiation process. Returned PSK must be * compatible with the selected cipher's digest. * * When negotiating TLS-PSK (pre-shared keys), this function is called * with the identity provided by the client. * If the return value is `null` the negotiation process will stop and an * "unknown_psk_identity" alert message will be sent to the other party. * If the server wishes to hide the fact that the PSK identity was not known, * the callback must provide some random data as `psk` to make the connection * fail with "decrypt_error" before negotiation is finished. * PSK ciphers are disabled by default, and using TLS-PSK thus * requires explicitly specifying a cipher suite with the `ciphers` option. * More information can be found in the RFC 4279. */ pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; /** * hint to send to a client to help * with selecting the identity during TLS-PSK negotiation. Will be ignored * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. */ pskIdentityHint?: string | undefined; } interface PSKCallbackNegotation { psk: DataView | NodeJS.TypedArray; identity: string; } interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { host?: string | undefined; port?: number | undefined; path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. socket?: net.Socket | undefined; // Establish secure connection on a given socket rather than creating a new socket checkServerIdentity?: typeof checkServerIdentity | undefined; servername?: string | undefined; // SNI TLS Extension session?: Buffer | undefined; minDHSize?: number | undefined; lookup?: net.LookupFunction | undefined; timeout?: number | undefined; /** * When negotiating TLS-PSK (pre-shared keys), this function is called * with optional identity `hint` provided by the server or `null` * in case of TLS 1.3 where `hint` was removed. * It will be necessary to provide a custom `tls.checkServerIdentity()` * for the connection as the default one will try to check hostname/IP * of the server against the certificate but that's not applicable for PSK * because there won't be a certificate present. * More information can be found in the RFC 4279. * * @param hint message sent from the server to help client * decide which identity to use during negotiation. * Always `null` if TLS 1.3 is used. * @returns Return `null` to stop the negotiation process. `psk` must be * compatible with the selected cipher's digest. * `identity` must use UTF-8 encoding. */ pskCallback?(hint: string | null): PSKCallbackNegotation | null; } class Server extends net.Server { constructor(secureConnectionListener?: (socket: TLSSocket) => void); constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); /** * The server.addContext() method adds a secure context that will be * used if the client request's SNI name matches the supplied hostname * (or wildcard). */ addContext(hostName: string, credentials: SecureContextOptions): void; /** * Returns the session ticket keys. */ getTicketKeys(): Buffer; /** * * The server.setSecureContext() method replaces the * secure context of an existing server. Existing connections to the * server are not interrupted. */ setSecureContext(details: SecureContextOptions): void; /** * The server.setSecureContext() method replaces the secure context of * an existing server. Existing connections to the server are not * interrupted. */ setTicketKeys(keys: Buffer): void; /** * events.EventEmitter * 1. tlsClientError * 2. newSession * 3. OCSPRequest * 4. resumeSession * 5. secureConnection * 6. keylog */ addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; addListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; addListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; on(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; once(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; once(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; prependListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; prependListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; prependOnceListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; prependOnceListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; } interface SecurePair { encrypted: TLSSocket; cleartext: TLSSocket; } type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; interface SecureContextOptions { /** * Optionally override the trusted CA certificates. Default is to trust * the well-known CAs curated by Mozilla. Mozilla's CAs are completely * replaced when CAs are explicitly specified using this option. */ ca?: string | Buffer | Array<string | Buffer> | undefined; /** * Cert chains in PEM format. One cert chain should be provided per * private key. Each cert chain should consist of the PEM formatted * certificate for a provided private key, followed by the PEM * formatted intermediate certificates (if any), in order, and not * including the root CA (the root CA must be pre-known to the peer, * see ca). When providing multiple cert chains, they do not have to * be in the same order as their private keys in key. If the * intermediate certificates are not provided, the peer will not be * able to validate the certificate, and the handshake will fail. */ cert?: string | Buffer | Array<string | Buffer> | undefined; /** * Colon-separated list of supported signature algorithms. The list * can contain digest algorithms (SHA256, MD5 etc.), public key * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). */ sigalgs?: string | undefined; /** * Cipher suite specification, replacing the default. For more * information, see modifying the default cipher suite. Permitted * ciphers can be obtained via tls.getCiphers(). Cipher names must be * uppercased in order for OpenSSL to accept them. */ ciphers?: string | undefined; /** * Name of an OpenSSL engine which can provide the client certificate. */ clientCertEngine?: string | undefined; /** * PEM formatted CRLs (Certificate Revocation Lists). */ crl?: string | Buffer | Array<string | Buffer> | undefined; /** * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use * openssl dhparam to create the parameters. The key length must be * greater than or equal to 1024 bits or else an error will be thrown. * Although 1024 bits is permissible, use 2048 bits or larger for * stronger security. If omitted or invalid, the parameters are * silently discarded and DHE ciphers will not be available. */ dhparam?: string | Buffer | undefined; /** * A string describing a named curve or a colon separated list of curve * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key * agreement. Set to auto to select the curve automatically. Use * crypto.getCurves() to obtain a list of available curve names. On * recent releases, openssl ecparam -list_curves will also display the * name and description of each available elliptic curve. Default: * tls.DEFAULT_ECDH_CURVE. */ ecdhCurve?: string | undefined; /** * Attempt to use the server's cipher suite preferences instead of the * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be * set in secureOptions */ honorCipherOrder?: boolean | undefined; /** * Private keys in PEM format. PEM allows the option of private keys * being encrypted. Encrypted keys will be decrypted with * options.passphrase. Multiple keys using different algorithms can be * provided either as an array of unencrypted key strings or buffers, * or an array of objects in the form {pem: <string|buffer>[, * passphrase: <string>]}. The object form can only occur in an array. * object.passphrase is optional. Encrypted keys will be decrypted with * object.passphrase if provided, or options.passphrase if it is not. */ key?: string | Buffer | Array<Buffer | KeyObject> | undefined; /** * Name of an OpenSSL engine to get private key from. Should be used * together with privateKeyIdentifier. */ privateKeyEngine?: string | undefined; /** * Identifier of a private key managed by an OpenSSL engine. Should be * used together with privateKeyEngine. Should not be set together with * key, because both options define a private key in different ways. */ privateKeyIdentifier?: string | undefined; /** * Optionally set the maximum TLS version to allow. One * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the * `secureProtocol` option, use one or the other. * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. */ maxVersion?: SecureVersion | undefined; /** * Optionally set the minimum TLS version to allow. One * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the * `secureProtocol` option, use one or the other. It is not recommended to use * less than TLSv1.2, but it may be required for interoperability. * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. */ minVersion?: SecureVersion | undefined; /** * Shared passphrase used for a single private key and/or a PFX. */ passphrase?: string | undefined; /** * PFX or PKCS12 encoded private key and certificate chain. pfx is an * alternative to providing key and cert individually. PFX is usually * encrypted, if it is, passphrase will be used to decrypt it. Multiple * PFX can be provided either as an array of unencrypted PFX buffers, * or an array of objects in the form {buf: <string|buffer>[, * passphrase: <string>]}. The object form can only occur in an array. * object.passphrase is optional. Encrypted PFX will be decrypted with * object.passphrase if provided, or options.passphrase if it is not. */ pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined; /** * Optionally affect the OpenSSL protocol behavior, which is not * usually necessary. This should be used carefully if at all! Value is * a numeric bitmask of the SSL_OP_* options from OpenSSL Options */ secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options /** * Legacy mechanism to select the TLS protocol version to use, it does * not support independent control of the minimum and maximum version, * and does not support limiting the protocol to TLSv1.3. Use * minVersion and maxVersion instead. The possible values are listed as * SSL_METHODS, use the function names as strings. For example, use * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow * any TLS protocol version up to TLSv1.3. It is not recommended to use * TLS versions less than 1.2, but it may be required for * interoperability. Default: none, see minVersion. */ secureProtocol?: string | undefined; /** * Opaque identifier used by servers to ensure session state is not * shared between applications. Unused by clients. */ sessionIdContext?: string | undefined; /** * 48-bytes of cryptographically strong pseudo-random data. * See Session Resumption for more information. */ ticketKeys?: Buffer | undefined; /** * The number of seconds after which a TLS session created by the * server will no longer be resumable. See Session Resumption for more * information. Default: 300. */ sessionTimeout?: number | undefined; } interface SecureContext { context: any; } /* * Verifies the certificate `cert` is issued to host `host`. * @host The hostname to verify the certificate against * @cert PeerCertificate representing the peer's certificate * * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. */ function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; /** * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. */ function createSecurePair(credentials?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; function createSecureContext(options?: SecureContextOptions): SecureContext; function getCiphers(): string[]; /** * The default curve name to use for ECDH key agreement in a tls server. * The default value is 'auto'. See tls.createSecureContext() for further * information. */ let DEFAULT_ECDH_CURVE: string; /** * The default value of the maxVersion option of * tls.createSecureContext(). It can be assigned any of the supported TLS * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to * 'TLSv1.3'. If multiple of the options are provided, the highest maximum * is used. */ let DEFAULT_MAX_VERSION: SecureVersion; /** * The default value of the minVersion option of tls.createSecureContext(). * It can be assigned any of the supported TLS protocol versions, * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless * changed using CLI options. Using --tls-min-v1.0 sets the default to * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options * are provided, the lowest minimum is used. */ let DEFAULT_MIN_VERSION: SecureVersion; /** * An immutable array of strings representing the root certificates (in PEM * format) used for verifying peer certificates. This is the default value * of the ca option to tls.createSecureContext(). */ const rootCertificates: ReadonlyArray<string>; }
the_stack
import classNames from "classnames"; import * as React from "react"; import { polyfill } from "react-lifecycles-compat"; import { AbstractPureComponent2, Classes, Keys } from "../../common"; import { DISPLAYNAME_PREFIX, IntentProps, Props } from "../../common/props"; import { clamp } from "../../common/utils"; import { Browser } from "../../compatibility"; // eslint-disable-next-line deprecation/deprecation export type EditableTextProps = IEditableTextProps; /** @deprecated use EditableTextProps */ export interface IEditableTextProps extends IntentProps, Props { /** * EXPERIMENTAL FEATURE. * * When true, this forces the component to _always_ render an editable input (or textarea) * both when the component is focussed and unfocussed, instead of the component's default * behavior of switching between a text span and a text input upon interaction. * * This behavior can help in certain applications where, for example, a custom right-click * context menu is used to supply clipboard copy and paste functionality. * * @default false */ alwaysRenderInput?: boolean; /** * If `true` and in multiline mode, the `enter` key will trigger onConfirm and `mod+enter` * will insert a newline. If `false`, the key bindings are inverted such that `enter` * adds a newline. * * @default false */ confirmOnEnterKey?: boolean; /** Default text value of uncontrolled input. */ defaultValue?: string; /** * Whether the text can be edited. * * @default false */ disabled?: boolean; /** Whether the component is currently being edited. */ isEditing?: boolean; /** Maximum number of characters allowed. Unlimited by default. */ maxLength?: number; /** Minimum width in pixels of the input, when not `multiline`. */ minWidth?: number; /** * Whether the component supports multiple lines of text. * This prop should not be changed during the component's lifetime. * * @default false */ multiline?: boolean; /** * Maximum number of lines before scrolling begins, when `multiline`. */ maxLines?: number; /** * Minimum number of lines (essentially minimum height), when `multiline`. * * @default 1 */ minLines?: number; /** * Placeholder text when there is no value. * * @default "Click to Edit" */ placeholder?: string; /** * Whether the entire text field should be selected on focus. * If `false`, the cursor is placed at the end of the text. * This prop is ignored on inputs with type other then text, search, url, tel and password. See https://html.spec.whatwg.org/multipage/input.html#do-not-apply for details. * * @default false */ selectAllOnFocus?: boolean; /** * The type of input that should be shown, when not `multiline`. */ type?: string; /** Text value of controlled input. */ value?: string; /** ID attribute to pass to the underlying element that contains the text contents. This allows for referencing via aria attributes */ contentId?: string; /** Callback invoked when user cancels input with the `esc` key. Receives last confirmed value. */ onCancel?(value: string): void; /** Callback invoked when user changes input in any way. */ onChange?(value: string): void; /** Callback invoked when user confirms value with `enter` key or by blurring input. */ onConfirm?(value: string): void; /** Callback invoked after the user enters edit mode. */ onEdit?(value: string | undefined): void; } export interface IEditableTextState { /** Pixel height of the input, measured from span size */ inputHeight?: number; /** Pixel width of the input, measured from span size */ inputWidth?: number; /** Whether the value is currently being edited */ isEditing?: boolean; /** The last confirmed value */ lastValue?: string; /** The controlled input value, may be different from prop during editing */ value?: string; } const BUFFER_WIDTH_DEFAULT = 5; const BUFFER_WIDTH_IE = 30; @polyfill export class EditableText extends AbstractPureComponent2<EditableTextProps, IEditableTextState> { public static displayName = `${DISPLAYNAME_PREFIX}.EditableText`; public static defaultProps: EditableTextProps = { alwaysRenderInput: false, confirmOnEnterKey: false, defaultValue: "", disabled: false, maxLines: Infinity, minLines: 1, minWidth: 80, multiline: false, placeholder: "Click to Edit", type: "text", }; private inputElement: HTMLInputElement | HTMLTextAreaElement | null = null; private valueElement: HTMLSpanElement | null = null; private refHandlers = { content: (spanElement: HTMLSpanElement | null) => { this.valueElement = spanElement; }, input: (input: HTMLInputElement | HTMLTextAreaElement | null) => { if (input != null) { this.inputElement = input; // temporary fix for #3882 if (!this.props.alwaysRenderInput) { this.inputElement.focus(); } if (this.state != null && this.state.isEditing) { const supportsSelection = inputSupportsSelection(input); if (supportsSelection) { const { length } = input.value; input.setSelectionRange(this.props.selectAllOnFocus ? 0 : length, length); } if (!supportsSelection || !this.props.selectAllOnFocus) { input.scrollLeft = input.scrollWidth; } } } }, }; public constructor(props: EditableTextProps, context?: any) { super(props, context); const value = props.value == null ? props.defaultValue : props.value; this.state = { inputHeight: 0, inputWidth: 0, isEditing: props.isEditing === true && props.disabled === false, lastValue: value, value, }; } public render() { const { alwaysRenderInput, disabled, multiline, contentId } = this.props; const value = this.props.value ?? this.state.value; const hasValue = value != null && value !== ""; const classes = classNames( Classes.EDITABLE_TEXT, Classes.intentClass(this.props.intent), { [Classes.DISABLED]: disabled, [Classes.EDITABLE_TEXT_EDITING]: this.state.isEditing, [Classes.EDITABLE_TEXT_PLACEHOLDER]: !hasValue, [Classes.MULTILINE]: multiline, }, this.props.className, ); let contentStyle: React.CSSProperties; if (multiline) { // set height only in multiline mode when not editing // otherwise we're measuring this element to determine appropriate height of text contentStyle = { height: !this.state.isEditing ? this.state.inputHeight : undefined }; } else { // minWidth only applies in single line mode (multiline == width 100%) contentStyle = { height: this.state.inputHeight, lineHeight: this.state.inputHeight != null ? `${this.state.inputHeight}px` : undefined, minWidth: this.props.minWidth, }; } // If we are always rendering an input, then NEVER make the container div focusable. // Otherwise, make container div focusable when not editing, so it can still be tabbed // to focus (when the input is rendered, it is itself focusable so container div doesn't need to be) const tabIndex = alwaysRenderInput || this.state.isEditing || disabled ? undefined : 0; // we need the contents to be rendered while editing so that we can measure their height // and size the container element responsively const shouldHideContents = alwaysRenderInput && !this.state.isEditing; const spanProps: React.HTMLProps<HTMLSpanElement> = contentId != null ? { id: contentId } : {}; return ( <div className={classes} onFocus={this.handleFocus} tabIndex={tabIndex}> {alwaysRenderInput || this.state.isEditing ? this.renderInput(value) : undefined} {shouldHideContents ? undefined : ( <span {...spanProps} className={Classes.EDITABLE_TEXT_CONTENT} ref={this.refHandlers.content} style={contentStyle} > {hasValue ? value : this.props.placeholder} </span> )} </div> ); } public componentDidMount() { this.updateInputDimensions(); } public componentDidUpdate(prevProps: EditableTextProps, prevState: IEditableTextState) { const newState: IEditableTextState = {}; // allow setting the value to undefined/null in controlled mode if (this.props.value !== prevProps.value && (prevProps.value != null || this.props.value != null)) { newState.value = this.props.value; } if (this.props.isEditing != null && this.props.isEditing !== prevProps.isEditing) { newState.isEditing = this.props.isEditing; } if (this.props.disabled || (this.props.disabled == null && prevProps.disabled)) { newState.isEditing = false; } this.setState(newState); if (this.state.isEditing && !prevState.isEditing) { this.props.onEdit?.(this.state.value); } // updateInputDimensions is an expensive method. Call it only when the props // it depends on change if ( this.state.value !== prevState.value || this.props.alwaysRenderInput !== prevProps.alwaysRenderInput || this.props.maxLines !== prevProps.maxLines || this.props.minLines !== prevProps.minLines || this.props.minWidth !== prevProps.minWidth || this.props.multiline !== prevProps.multiline ) { this.updateInputDimensions(); } } public cancelEditing = () => { const { lastValue, value } = this.state; this.setState({ isEditing: false, value: lastValue }); if (value !== lastValue) { this.props.onChange?.(lastValue!); } this.props.onCancel?.(lastValue!); }; public toggleEditing = () => { if (this.state.isEditing) { const { value } = this.state; this.setState({ isEditing: false, lastValue: value }); this.props.onConfirm?.(value!); } else if (!this.props.disabled) { this.setState({ isEditing: true }); } }; private handleFocus = () => { const { alwaysRenderInput, disabled, selectAllOnFocus } = this.props; if (!disabled) { this.setState({ isEditing: true }); } if (alwaysRenderInput && selectAllOnFocus && this.inputElement != null) { const { length } = this.inputElement.value; this.inputElement.setSelectionRange(0, length); } }; private handleTextChange = (event: React.FormEvent<HTMLElement>) => { const value = (event.target as HTMLInputElement).value; // state value should be updated only when uncontrolled if (this.props.value == null) { this.setState({ value }); } this.props.onChange?.(value); }; private handleKeyEvent = (event: React.KeyboardEvent<HTMLElement>) => { // HACKHACK: https://github.com/palantir/blueprint/issues/4165 /* eslint-disable-next-line deprecation/deprecation */ const { altKey, ctrlKey, metaKey, shiftKey, which } = event; if (which === Keys.ESCAPE) { this.cancelEditing(); return; } const hasModifierKey = altKey || ctrlKey || metaKey || shiftKey; if (which === Keys.ENTER) { // prevent IE11 from full screening with alt + enter // shift + enter adds a newline by default if (altKey || shiftKey) { event.preventDefault(); } if (this.props.confirmOnEnterKey && this.props.multiline) { if (event.target != null && hasModifierKey) { insertAtCaret(event.target as HTMLTextAreaElement, "\n"); this.handleTextChange(event); } else { this.toggleEditing(); } } else if (!this.props.multiline || hasModifierKey) { this.toggleEditing(); } } }; private renderInput(value: string | undefined) { const { disabled, maxLength, multiline, type, placeholder } = this.props; const props: React.InputHTMLAttributes<HTMLInputElement | HTMLTextAreaElement> = { className: Classes.EDITABLE_TEXT_INPUT, disabled, maxLength, onBlur: this.toggleEditing, onChange: this.handleTextChange, onKeyDown: this.handleKeyEvent, placeholder, value, }; const { inputHeight, inputWidth } = this.state; if (inputHeight !== 0 && inputWidth !== 0) { props.style = { height: inputHeight, lineHeight: !multiline && inputHeight != null ? `${inputHeight}px` : undefined, width: multiline ? "100%" : inputWidth, }; } return multiline ? ( <textarea ref={this.refHandlers.input} {...props} /> ) : ( <input ref={this.refHandlers.input} type={type} {...props} /> ); } private updateInputDimensions() { if (this.valueElement != null) { const { maxLines, minLines, minWidth, multiline } = this.props; const { parentElement, textContent } = this.valueElement; let { scrollHeight, scrollWidth } = this.valueElement; const lineHeight = getLineHeight(this.valueElement); // add one line to computed <span> height if text ends in newline // because <span> collapses that trailing whitespace but <textarea> shows it if (multiline && this.state.isEditing && /\n$/.test(textContent ?? "")) { scrollHeight += lineHeight; } if (lineHeight > 0) { // line height could be 0 if the isNaN block from getLineHeight kicks in scrollHeight = clamp(scrollHeight, minLines! * lineHeight, maxLines! * lineHeight); } // Chrome's input caret height misaligns text so the line-height must be larger than font-size. // The computed scrollHeight must also account for a larger inherited line-height from the parent. scrollHeight = Math.max(scrollHeight, getFontSize(this.valueElement) + 1, getLineHeight(parentElement!)); // Need to add a small buffer so text does not shift prior to resizing, causing an infinite loop. // IE needs a larger buffer than other browsers. scrollWidth += Browser.isInternetExplorer() ? BUFFER_WIDTH_IE : BUFFER_WIDTH_DEFAULT; this.setState({ inputHeight: scrollHeight, inputWidth: Math.max(scrollWidth, minWidth!), }); // synchronizes the ::before pseudo-element's height while editing for Chrome 53 if (multiline && this.state.isEditing) { this.setTimeout(() => (parentElement!.style.height = `${scrollHeight}px`)); } } } } function getFontSize(element: HTMLElement) { const fontSize = getComputedStyle(element).fontSize; return fontSize === "" ? 0 : parseInt(fontSize.slice(0, -2), 10); } function getLineHeight(element: HTMLElement) { // getComputedStyle() => 18.0001px => 18 let lineHeight = parseInt(getComputedStyle(element).lineHeight.slice(0, -2), 10); // this check will be true if line-height is a keyword like "normal" if (isNaN(lineHeight)) { // @see http://stackoverflow.com/a/18430767/6342931 const line = document.createElement("span"); line.innerHTML = "<br>"; element.appendChild(line); const singleLineHeight = element.offsetHeight; line.innerHTML = "<br><br>"; const doubleLineHeight = element.offsetHeight; element.removeChild(line); // this can return 0 in edge cases lineHeight = doubleLineHeight - singleLineHeight; } return lineHeight; } function insertAtCaret(el: HTMLTextAreaElement, text: string) { const { selectionEnd, selectionStart, value } = el; if (selectionStart >= 0) { const before = value.substring(0, selectionStart); const after = value.substring(selectionEnd, value.length); const len = text.length; el.value = `${before}${text}${after}`; el.selectionStart = selectionStart + len; el.selectionEnd = selectionStart + len; } } function inputSupportsSelection(input: HTMLInputElement | HTMLTextAreaElement) { switch (input.type) { // HTMLTextAreaElement case "textarea": return true; // HTMLInputElement // see https://html.spec.whatwg.org/multipage/input.html#do-not-apply case "text": case "search": case "tel": case "url": case "password": return true; default: return false; } }
the_stack
import * as d3 from 'd3'; import * as _ from "lodash" import * as R from 'ramda' import * as tp from '../etc/types'; import * as rsp from '../api/responses'; import '../etc/xd3' import { API } from '../api/mainApi' import { UIConfig } from '../uiConfig' import { TextTokens, LeftTextToken, RightTextToken } from './TextToken' import { AttentionHeadBox, getAttentionInfo } from './AttentionHeadBox' import { AttentionGraph } from './AttentionConnector' import { CorpusInspector } from './CorpusInspector' import { TokenWrapper, sideToLetter } from '../data/TokenWrapper' import { AttentionWrapper, makeFromMetaResponse } from '../data/AttentionCapsule' import { SimpleEventHandler } from '../etc/SimpleEventHandler' import { CorpusMatManager } from '../vis/CorpusMatManager' import { CorpusHistogram } from '../vis/CorpusHistogram' import { FaissSearchResultWrapper } from '../data/FaissSearchWrapper' import { D3Sel, Sel } from '../etc/Util'; import { from, fromEvent, interval } from 'rxjs' import { switchMap, map, tap } from 'rxjs/operators' import { BaseType } from "d3"; import { SimpleMeta } from "../etc/types"; import ChangeEvent = JQuery.ChangeEvent; function isNullToken(tok: tp.TokenEvent) { const isSomeNull = x => { return (x == null) || (x == "null") } const tokIsNull = tok == null; const tokHasNull = isSomeNull(tok.side) || isSomeNull(tok.ind) return tokIsNull || tokHasNull } function showBySide(e: tp.TokenEvent) { // Check if saved token in uiConf is null if (!isNullToken(e)) { const classSelector = e.side == "left" ? "src-idx" : "target-idx"; Sel.setHidden(".atn-curve") Sel.setVisible(`.atn-curve[${classSelector}='${e.ind}']`) } } function chooseShowBySide(savedEvent: tp.TokenEvent, newEvent: tp.TokenEvent) { if (isNullToken(savedEvent)) { showBySide(newEvent) } } function chooseShowAll(savedEvent: tp.TokenEvent) { if (isNullToken(savedEvent)) Sel.setVisible(".atn-curve") } function unselectHead(head: number) { const affectedHeads = d3.selectAll(`.att-rect[head='${head}']`); affectedHeads.classed("unselected", true) } function selectHead(head: number) { const affectedHeads = d3.selectAll(`.att-rect[head='${head}']`); affectedHeads.classed("unselected", false) } function setSelDisabled(attr: boolean, sel: D3Sel) { const val = attr ? true : null sel.attr('disabled', val) } export class MainGraphic { api: API uiConf: UIConfig attCapsule: AttentionWrapper tokCapsule: TokenWrapper sels: any // Contains initial d3 selections of objects vizs: any // Contains vis components wrapped around parent sel eventHandler: SimpleEventHandler // Orchestrates events raised from components constructor() { this.api = new API() this.uiConf = new UIConfig() this.skeletonInit() this.mainInit(); } /** * Functions that can be called without any information of a response. * * This should be called once and only once */ skeletonInit() { this.sels = { body: d3.select('body'), atnContainer: d3.select('#atn-container'), atnDisplay: d3.select("#atn-display"), modelSelector: d3.select("#model-option-selector"), corpusSelector: d3.select("#corpus-select"), atnHeads: { left: d3.select("#left-att-heads"), right: d3.select("#right-att-heads"), headInfo: d3.select("#head-info-box") .classed('mat-hover-display', true) .classed('text-center', true) .style('width', String(70) + 'px') .style('height', String(30) + 'px') .style('visibillity', 'hidden') }, form: { sentenceA: d3.select("#form-sentence-a"), button: d3.select("#update-sentence"), }, tokens: { left: d3.select("#left-tokens"), right: d3.select("#right-tokens"), }, clsToggle: d3.select("#cls-toggle").select(".switch"), layerCheckboxes: d3.select("#layer-select"), headCheckboxes: d3.select("#head-select"), contextQuery: d3.select("#search-contexts"), embeddingQuery: d3.select("#search-embeddings"), selectedHeads: d3.select("#selected-heads"), headSelectAll: d3.select("#select-all-heads"), headSelectNone: d3.select("#select-no-heads"), testCheckbox: d3.select("#simple-embed-query"), threshSlider: d3.select("#my-range"), corpusInspector: d3.select("#corpus-similar-sentences-div"), corpusMatManager: d3.select("#corpus-mat-container"), corpusMsgBox: d3.select("#corpus-msg-box"), histograms: { matchedWordDescription: d3.select("#match-kind"), matchedWord: d3.select("#matched-histogram-container"), maxAtt: d3.select("#max-att-histogram-container"), }, buttons: { killLeft: d3.select("#kill-left"), addLeft: d3.select("#minus-left"), addRight: d3.select("#plus-right"), killRight: d3.select("#kill-right"), refresh: d3.select("#mat-refresh") }, metaSelector: { matchedWord: d3.select("#matched-meta-select"), maxAtt: d3.select("#max-att-meta-select") } } this.eventHandler = new SimpleEventHandler(<Element>this.sels.body.node()); this.vizs = { leftHeads: new AttentionHeadBox(this.sels.atnHeads.left, this.eventHandler, { side: "left", }), rightHeads: new AttentionHeadBox(this.sels.atnHeads.right, this.eventHandler, { side: "right" }), tokens: { left: new LeftTextToken(this.sels.tokens.left, this.eventHandler), right: new RightTextToken(this.sels.tokens.right, this.eventHandler), }, attentionSvg: new AttentionGraph(this.sels.atnDisplay, this.eventHandler), corpusInspector: new CorpusInspector(this.sels.corpusInspector, this.eventHandler), corpusMatManager: new CorpusMatManager(this.sels.corpusMatManager, this.eventHandler, { idxs: this.uiConf.offsetIdxs() }), histograms: { matchedWord: new CorpusHistogram(this.sels.histograms.matchedWord, this.eventHandler), maxAtt: new CorpusHistogram(this.sels.histograms.maxAtt, this.eventHandler), }, } this._bindEventHandler() this._initModelSelection(); this._initCorpusSelection(); } private mainInit() { const self = this; this.sels.body.style("cursor", "progress") this.api.getModelDetails(this.uiConf.model()).then(md => { const val = md.payload this.uiConf.nLayers(val.nlayers).nHeads(val.nheads) this.initLayers(this.uiConf.nLayers()) this.api.getMetaAttentions(this.uiConf.model(), this.uiConf.sentence(), this.uiConf.layer()).then(attention => { const att = attention.payload; this.initFromResponse(att) // Wrap postInit into function so asynchronous call does not mess with necessary inits const postResponseDisplayCleanup = () => { this._toggleTokenSel() const toDisplay = this.uiConf.displayInspector() this._searchDisabler() if (toDisplay == 'context') { this._queryContext() } else if (toDisplay == 'embeddings') { this._queryEmbeddings() } } let normBy if ((this.uiConf.modelKind() == tp.ModelKind.Autoregressive) && (!this.uiConf.hideClsSep())) { normBy = tp.NormBy.Col } else { normBy = tp.NormBy.All } this.vizs.attentionSvg.normBy = normBy if (this.uiConf.maskInds().length > 0) { this.tokCapsule.a.maskInds = this.uiConf.maskInds() this.api.updateMaskedAttentions(this.uiConf.model(), this.tokCapsule.a, this.uiConf.sentence(), this.uiConf.layer()).then(resp => { const r = resp.payload; this.attCapsule.updateFromNormal(r, this.uiConf.hideClsSep()); this.tokCapsule.updateTokens(r) this.update() postResponseDisplayCleanup() }) } else { this.update() postResponseDisplayCleanup() } if (this.uiConf.modelKind() == tp.ModelKind.Autoregressive) { // Ensure only 1 mask ind is present for autoregressive models if (this.uiConf.hasToken()) { this.grayToggle(<number>this.uiConf.token().ind) } self.vizs.tokens.left.options.divHover.textInfo = "Would predict next..." self.vizs.tokens.right.options.divHover.textInfo = "Would predict next..." } else { self.vizs.tokens.left.options.divHover.textInfo = "Would predict here..." self.vizs.tokens.right.options.divHover.textInfo = "Would predict here..." } this.sels.body.style("cursor", "default") }); }) } private initFromResponse(attention: tp.AttentionResponse) { this.attCapsule = makeFromMetaResponse(attention, this.uiConf.hideClsSep()) this.tokCapsule = new TokenWrapper(attention); this._staticInits() } private leaveCorpusMsg(msg: string) { this.vizs.corpusInspector.hideView() this.vizs.corpusMatManager.hideView() console.log("Running leave msg"); Sel.unhideElement(this.sels.corpusMsgBox) this.sels.corpusMsgBox.text(msg) } private _bindEventHandler() { const self = this; this.eventHandler.bind(TextTokens.events.tokenDblClick, (e) => { switch (self.uiConf.modelKind()) { case tp.ModelKind.Bidirectional: { e.sel.classed("masked-token", !e.sel.classed("masked-token")); const letter = sideToLetter(e.side, this.uiConf.attType) self.tokCapsule[letter].toggle(e.ind) self.sels.body.style("cursor", "progress") self.api.updateMaskedAttentions(this.uiConf.model(), this.tokCapsule.a, this.uiConf.sentence(), this.uiConf.layer()).then((resp: rsp.AttentionDetailsResponse) => { const r = resp.payload; self.attCapsule.updateFromNormal(r, this.uiConf.hideClsSep()); self.tokCapsule.updateTokens(r); self.uiConf.maskInds(this.tokCapsule.a.maskInds) self.update(); self.sels.body.style("cursor", "default") }) break; } case tp.ModelKind.Autoregressive: { console.log("Autoregressive model doesn't do masking"); break; } default: { console.log("What kind of model is this?"); break; } } }) this.eventHandler.bind(TextTokens.events.tokenMouseOver, (e: tp.TokenEvent) => { chooseShowBySide(this.uiConf.token(), e) }) this.eventHandler.bind(TextTokens.events.tokenMouseOut, (e) => { chooseShowAll(this.uiConf.token()) }) this.eventHandler.bind(TextTokens.events.tokenClick, (e: tp.TokenEvent) => { const tokToggle = () => { this.uiConf.toggleToken(e) this._toggleTokenSel() showBySide(e) } tokToggle() this.renderAttHead() }) this.eventHandler.bind(AttentionHeadBox.events.rowMouseOver, (e: tp.HeadBoxEvent) => { self.sels.atnHeads.headInfo.style('visibility', 'visible') }) this.eventHandler.bind(AttentionHeadBox.events.rowMouseOut, () => { self.sels.atnHeads.headInfo.style('visibility', 'hidden') // Don't do anything special on row mouse out }) this.eventHandler.bind(AttentionHeadBox.events.boxMouseOver, (e: tp.HeadBoxEvent) => { const updateMat = this.attCapsule.byHead(e.head) this.vizs.attentionSvg.data(updateMat) this.vizs.attentionSvg.update(updateMat) showBySide(this.uiConf.token()) }) this.eventHandler.bind(AttentionHeadBox.events.boxMouseOut, () => { const att = this.attCapsule.byHeads(this.uiConf.heads()) this.vizs.attentionSvg.data(att) this.vizs.attentionSvg.update(att) showBySide(this.uiConf.token()) }) this.eventHandler.bind(AttentionHeadBox.events.boxMouseMove, (e) => { const headInfo = self.sels.atnHeads.headInfo let left, top, borderRadius if (e.side == "left") { const divOffset = [12, 3] left = e.mouse[0] + e.baseX - (+headInfo.style('width').replace('px', '') + divOffset[0]) top = e.mouse[1] + e.baseY - (+headInfo.style('height').replace('px', '') + divOffset[1]) borderRadius = "8px 8px 1px 8px" } else { const divOffset = [-13, 3] left = e.mouse[0] + e.baseX + divOffset[0] top = e.mouse[1] + e.baseY - (+headInfo.style('height').replace('px', '') + divOffset[1]) borderRadius = "8px 8px 8px 1px" } headInfo .style('visibility', 'visible') .style('left', String(left) + 'px') .style('top', String(top) + 'px') .style('border-radius', borderRadius) .text(`Head: ${e.ind + 1}`) // Don't do anything special on row mouse over }) this.eventHandler.bind(AttentionHeadBox.events.boxClick, (e: { head }) => { const result = this.uiConf.toggleHead(e.head) if (result == tp.Toggled.ADDED) { selectHead(e.head) } else if (result == tp.Toggled.REMOVED) { unselectHead(e.head) } this._searchDisabler() this._renderHeadSummary(); this.renderSvg(); }) this.eventHandler.bind(CorpusMatManager.events.mouseOver, (e: { val: "pos" | "dep" | "is_ent", offset: number }) => { // Uncomment the below if you want to modify the whole column // const selector = `.inspector-cell[index-offset='${e.offset}']` // d3.selectAll(selector).classed("hovered-col", true) }) this.eventHandler.bind(CorpusMatManager.events.mouseOut, (e: { offset: number, idx: number }) => { // Uncomment the below if you want to modify the whole column // const selector = `.inspector-cell[index-offset='${e.offset}']` // d3.selectAll(selector).classed("hovered-col", false) }) this.eventHandler.bind(CorpusMatManager.events.rectMouseOver, (e: { offset: number, idx: number }) => { const row = d3.select(`.inspector-row[rownum='${e.idx}']`) const word = row.select(`.inspector-cell[index-offset='${e.offset}']`) word.classed("hovered-col", true) }) this.eventHandler.bind(CorpusMatManager.events.rectMouseOut, (e: { offset: number, idx: number }) => { const row = d3.select(`.inspector-row[rownum='${e.idx}']`) const word = row.select(`.inspector-cell[index-offset='${e.offset}']`) word.classed("hovered-col", false) }) } private _toggleTokenSel() { const e = this.uiConf.token() const alreadySelected = d3.select('.selected-token') // If no token should be selected, unselect all tokens if (!this.uiConf.hasToken()) { const newSel: d3.Selection<BaseType, any, BaseType, any> = d3.selectAll('.selected-token') if (!newSel.empty()) newSel.classed('selected-token', false) } // Otherwise, select the indicated token else { const token2String = (e: tp.TokenEvent) => `#${e.side}-token-${e.ind}` const newSel = d3.select(token2String(e)) // Check that selection exists if (!newSel.empty()) newSel.classed('selected-token', true) } // Remove previous token selection, if any if (!alreadySelected.empty()) { alreadySelected.classed('selected-token', false) } if (this.uiConf.modelKind() == tp.ModelKind.Autoregressive) { this.grayToggle(+e.ind) this.markNextToggle(+e.ind, this.tokCapsule.a.length()) } this._searchDisabler() } /** Gray all tokens that have index greater than ind */ private grayBadToks(ind: number) { if (this.uiConf.modelKind() == tp.ModelKind.Autoregressive) { const grayToks = function (d, i) { const s = d3.select(this) s.classed("masked-token", i > ind) } d3.selectAll('.right-token').each(grayToks) d3.selectAll('.left-token').each(grayToks) } } private grayToggle(ind: number) { if (this.uiConf.hasToken()) this.grayBadToks(ind) else d3.selectAll('.token').classed('masked-token', false) } private markNextWordToks(ind: number, N: number) { const markToks = function (d, i) { const s = d3.select(this) s.classed("next-token", i == Math.min(ind + 1, N)) } d3.selectAll('.right-token').each(markToks) d3.selectAll('.left-token').each(markToks) } private markNextToggle(ind: number, N: number) { if (this.uiConf.hasToken()) this.markNextWordToks(ind, N) else d3.selectAll('.token').classed('next-token', false) } private _initModelSelection() { const self = this this.api.getSupportedModels().then(data => { const desc = data.descriptions if (data.force) { this.uiConf.model(desc[0].name) this.uiConf.modelKind(desc[0].kind) } const names = R.map(R.prop('name'))(desc) const kinds = R.map(R.prop('kind'))(desc) const kindmap = R.zipObj(names, kinds) this.sels.modelSelector.selectAll('.model-option') .data(desc) .join('option') .classed('model-option', true) .property('value', d => d.name) .attr("modelkind", d => d.kind) .text(d => d.name) this.sels.modelSelector.property('value', this.uiConf.model()); this.sels.modelSelector.on('change', function () { const me = d3.select(this) const mname = me.property('value') self.uiConf.model(mname); self.uiConf.modelKind(kindmap[mname]); if (kindmap[mname] == tp.ModelKind.Autoregressive) { console.log("RESETTING MASK INDS"); self.uiConf.maskInds([]) } self.mainInit(); }) }) } private _initCorpusSelection() { const self = this this.api.getSupportedCorpora().then(data => { self.uiConf.corpus(data[0].code) self.sels.corpusSelector.selectAll('option') .data(data) .join('option') .property('value', d => d.code) .text(d => d.display) this.sels.corpusSelector.on('change', function () { const me = d3.select(this) self.uiConf.corpus(me.property('value')) console.log(self.uiConf.corpus()); }) }) } private _staticInits() { this._initSentenceForm(); this._initQueryForm(); this._initAdder(); this._renderHeadSummary(); this._initMetaSelectors(); this._initToggle(); this.renderAttHead(); this.renderTokens(); } private _initAdder() { const updateUrlOffsetIdxs = () => { this.uiConf.offsetIdxs(this.vizs.corpusMatManager.idxs) } const fixCorpusMatHeights = () => { const newWrapped = this._wrapResults(this.vizs.corpusMatManager.data()) this.vizs.corpusMatManager.data(newWrapped.data) updateUrlOffsetIdxs() } this.sels.buttons.addRight.on('click', () => { this.vizs.corpusMatManager.addRight() updateUrlOffsetIdxs() }) this.sels.buttons.addLeft.on('click', () => { this.vizs.corpusMatManager.addLeft() updateUrlOffsetIdxs() }) this.sels.buttons.killRight.on('click', () => { this.vizs.corpusMatManager.killRight() updateUrlOffsetIdxs() }) this.sels.buttons.killLeft.on('click', () => { this.vizs.corpusMatManager.killLeft() updateUrlOffsetIdxs() }) this.sels.buttons.refresh.on('click', () => { fixCorpusMatHeights(); }) const onresize = () => { if (this.sels.corpusInspector.text() != '') fixCorpusMatHeights(); } window.onresize = onresize } private _initMetaSelectors() { this._initMatchedWordSelector(this.sels.metaSelector.matchedWord) this._initMaxAttSelector(this.sels.metaSelector.maxAtt) } private _initMaxAttSelector(sel: D3Sel) { const self = this; const chooseSelected = (value) => { const ms = sel.selectAll('label') ms.classed('active', false) const el = sel.selectAll(`label[value=${value}]`) el.classed('active', true) } chooseSelected(this.uiConf.metaMax()) const el = sel.selectAll('label') el.on('click', function () { const val = <SimpleMeta>d3.select(this).attr('value'); // Do toggle sel.selectAll('.active').classed('active', false) d3.select(this).classed('active', true) self.uiConf.metaMax(val) self.vizs.histograms.maxAtt.meta(val) }) } private _initMatchedWordSelector(sel: D3Sel) { const self = this; const chooseSelected = (value) => { const ms = sel.selectAll('label') ms.classed('active', false) const el = sel.selectAll(`label[value=${value}]`) el.classed('active', true) } chooseSelected(this.uiConf.metaMatch()) const el = sel.selectAll('label') el.on('click', function () { const val = <SimpleMeta>d3.select(this).attr('value') // Do toggle sel.selectAll('.active').classed('active', false) d3.select(this).classed('active', true) self.uiConf.metaMatch(val) self._updateCorpusInspectorFromMeta(val) }) } private _disableSearching(attr: boolean) { setSelDisabled(attr, this.sels.contextQuery) setSelDisabled(attr, this.sels.embeddingQuery) } private _updateCorpusInspectorFromMeta(val: tp.SimpleMeta) { this.vizs.corpusInspector.showNext(this.uiConf.showNext) this.vizs.corpusMatManager.pick(val) this.vizs.histograms.matchedWord.meta(val) } private _initSentenceForm() { const self = this; this.sels.form.sentenceA.attr('placeholder', "Enter new sentence to analyze") this.sels.form.sentenceA.attr('value', this.uiConf.sentence()) const clearInspector = () => { self.vizs.corpusMatManager.clear(); self.vizs.corpusInspector.clear(); self.vizs.histograms.matchedWord.clear(); self.vizs.histograms.maxAtt.clear(); } const submitNewSentence = () => { // replace all occurences of '#' in sentence as this causes the API to break const sentence_a: string = this.sels.form.sentenceA.property("value").replace(/\#/g, '') // Only update if the form is filled correctly if (sentence_a.length) { this.sels.body.style("cursor", "progress") this.api.getMetaAttentions(this.uiConf.model(), sentence_a, this.uiConf.layer()) .then((resp: rsp.AttentionDetailsResponse) => { const r = resp.payload this.uiConf.sentence(sentence_a) this.uiConf.rmToken(); this.attCapsule.updateFromNormal(r, this.uiConf.hideClsSep()); this.tokCapsule.updateFromResponse(r); this._toggleTokenSel(); this.update(); clearInspector(); this.sels.body.style("cursor", "default") }) } } const onEnter = R.curry((keyCode, f, event) => { const e = event || window.event; if (e.keyCode !== keyCode) return; e.preventDefault(); f(); }) const onEnterSubmit = onEnter(13, submitNewSentence) const btn = this.sels.form.button; const inputBox = this.sels.form.sentenceA; btn.on("click", submitNewSentence) inputBox.on('keypress', onEnterSubmit) } private _getSearchEmbeds() { const savedToken = this.uiConf.token(); const out = this.vizs.tokens[savedToken.side].getEmbedding(savedToken.ind) return out.embeddings } private _getSearchContext() { const savedToken = this.uiConf.token(); const out = this.vizs.tokens[savedToken.side].getEmbedding(savedToken.ind) return out.contexts } private _searchEmbeddings() { const self = this; console.log("SEARCHING EMBEDDINGS"); const embed = this._getSearchEmbeds() const layer = self.uiConf.layer() const heads = self.uiConf.heads() const k = 50 self.vizs.corpusInspector.showNext(self.uiConf.showNext) this.sels.body.style("cursor", "progress") self.api.getNearestEmbeddings(self.uiConf.model(), self.uiConf.corpus(), embed, layer, heads, k) .then((val: rsp.NearestNeighborResponse) => { if (val.status == 406) { self.leaveCorpusMsg(`Embeddings are not available for model '${self.uiConf.model()}' and corpus '${self.uiConf.corpus()}' at this time.`) } else { const v = val.payload self.vizs.corpusInspector.unhideView() self.vizs.corpusMatManager.unhideView() // Get heights of corpus inspector rows. self.vizs.corpusInspector.update(v) const wrappedVals = self._wrapResults(v) const countedVals = wrappedVals.getMatchedHistogram() const offsetVals = wrappedVals.getMaxAttHistogram() self.vizs.corpusMatManager.update(wrappedVals.data) self.sels.histograms.matchedWordDescription.text(this.uiConf.matchHistogramDescription) console.log("MATCHER: ", self.sels.histograms.matchedWord); self.vizs.histograms.matchedWord.update(countedVals) self.vizs.histograms.maxAtt.update(offsetVals) self.uiConf.displayInspector('embeddings') this._updateCorpusInspectorFromMeta(this.uiConf.metaMatch()) } this.sels.body.style("cursor", "default") }) } private _searchContext() { const self = this; console.log("SEARCHING CONTEXTS"); const context = this._getSearchContext() const layer = self.uiConf.layer() const heads = self.uiConf.heads() const k = 50 self.vizs.corpusInspector.showNext(self.uiConf.showNext) this.sels.body.style("cursor", "progress") self.api.getNearestContexts(self.uiConf.model(), self.uiConf.corpus(), context, layer, heads, k) .then((val: rsp.NearestNeighborResponse) => { // Get heights of corpus inspector rows. if (val.status == 406) { console.log("Contexts are not available!"); self.leaveCorpusMsg(`Contexts are not available for model '${self.uiConf.model()}' and corpus '${self.uiConf.corpus()}' at this time.`) } else { const v = val.payload; console.log("HIDING"); self.vizs.corpusInspector.update(v) Sel.hideElement(self.sels.corpusMsgBox) self.vizs.corpusInspector.unhideView() self.vizs.corpusMatManager.unhideView() const wrappedVals = self._wrapResults(v) const countedVals = wrappedVals.getMatchedHistogram() const offsetVals = wrappedVals.getMaxAttHistogram() self.vizs.corpusMatManager.update(wrappedVals.data) self.vizs.histograms.matchedWord.update(countedVals) self.vizs.histograms.maxAtt.update(offsetVals) self.uiConf.displayInspector('context') this._updateCorpusInspectorFromMeta(this.uiConf.metaMatch()) self.vizs.histograms.maxAtt.meta(self.uiConf.metaMax()) } this.sels.body.style("cursor", "default") }) } private _queryContext() { const self = this; if (this.uiConf.hasToken()) { this._searchContext(); } else { console.log("Was told to show inspector but was not given a selected token embedding") } } private _queryEmbeddings() { const self = this; if (this.uiConf.hasToken()) { console.log("token: ", this.uiConf.token()); this._searchEmbeddings(); } else { console.log("Was told to show inspector but was not given a selected token embedding") } } private _searchingDisabled() { return (this.uiConf.heads().length == 0) || (!this.uiConf.hasToken()) } private _searchDisabler() { this._disableSearching(this._searchingDisabled()) } private _initQueryForm() { const self = this; this._searchDisabler() this.sels.contextQuery.on("click", () => { self._queryContext() }) this.sels.embeddingQuery.on("click", () => { self._queryEmbeddings() }) } private _renderHeadSummary() { this.sels.selectedHeads .html(R.join(', ', this.uiConf.heads().map(h => h + 1))) } // Modify faiss results with corresponding heights private _wrapResults(returnedFaissResults: tp.FaissSearchResults[]) { const rows = d3.selectAll('.inspector-row') // Don't just use offsetHeight since that rounds to the nearest integer const heights = rows.nodes().map((n: HTMLElement) => n.getBoundingClientRect().height) const newVals = returnedFaissResults.map((v, i) => { return R.assoc('height', heights[i], v) }) const wrappedVals = new FaissSearchResultWrapper(newVals, this.uiConf.showNext) return wrappedVals } private initLayers(nLayers: number) { const self = this; let hasActive = false; const checkboxes = self.sels.layerCheckboxes.selectAll(".layerCheckbox") .data(_.range(0, nLayers)) .join("label") .attr("class", "btn button layerCheckbox") .classed('active', (d, i) => { // Assign to largest layer available if uiConf.layer() > new nLayers if (d == self.uiConf.layer()) { // Javascript is 0 indexed! hasActive = true; return true } if (!hasActive && d == nLayers) { self.uiConf.layer(d) hasActive = true return true } return false }) .text((d) => d + 1) .append("input") .attr("type", "radio") .attr("class", "checkbox-inline") .attr("name", "layerbox") // .attr("head", d => d) .attr("id", (d, i) => "layerCheckbox" + i) // .text((d, i) => d + " ") fromEvent(checkboxes.nodes(), 'change').pipe( tap((e: Event) => { const myData = d3.select(<BaseType>e.target).datum(); console.log(myData, "--- myData"); this.sels.layerCheckboxes.selectAll(".layerCheckbox") .classed('active', d => d === myData) }), map((v: Event) => +d3.select(<BaseType>v.target).datum()), tap(v => { console.log("New layer: ", v); self.uiConf.layer(v); self.sels.body.style("cursor", "progress"); }), switchMap((v) => from(self.api.updateMaskedAttentions(self.uiConf.model(), self.tokCapsule.a, self.uiConf.sentence(), v))) ).subscribe({ next: (resp: rsp.AttentionDetailsResponse) => { const r = resp.payload; self.attCapsule.updateFromNormal(r, this.uiConf.hideClsSep()); self.tokCapsule.updateTokens(r); self.uiConf.maskInds(self.tokCapsule.a.maskInds) self.update(); self.sels.body.style("cursor", "default") self._toggleTokenSel(); } }) const layerId = `#layerCheckbox${this.uiConf.layer()}` console.log("Layer ID: ", layerId); d3.select(layerId).attr("checked", "checked") // Init threshold stuff const dispThresh = (thresh) => Math.round(thresh * 100) d3.select('#my-range-value').text(dispThresh(self.uiConf.threshold())) this.sels.threshSlider.on("input", _.throttle(function () { const node = <HTMLInputElement>this; self.uiConf.threshold(+node.value / 100); d3.select('#my-range-value').text(dispThresh(self.uiConf.threshold())) self.vizs.attentionSvg.threshold(self.uiConf.threshold()) }, 100)) this.sels.headSelectAll.on("click", function () { self.uiConf.selectAllHeads(); self._searchDisabler() self.renderSvg() self.renderAttHead() }) this.sels.headSelectNone.on("click", function () { self.uiConf.selectNoHeads(); self._searchDisabler(); self.renderSvg() self.renderAttHead() Sel.setHidden(".atn-curve") }) } _initToggle() { fromEvent(this.sels.clsToggle.node(), 'input').pipe( // @ts-ignore -- TODO: FIX ! map(e => e.srcElement.checked), ).subscribe({ next: v => { this.uiConf.hideClsSep(v) this.attCapsule.zeroed(v) this.renderSvg(); this.renderAttHead(); } }) } renderAttHead() { const heads = _.range(0, this.uiConf._nHeads) const focusAtt = this.attCapsule.att const token = this.uiConf.hasToken() ? this.uiConf.token() : null //@ts-ignore const leftAttInfo = getAttentionInfo(focusAtt, heads, "left", token); //@ts-ignore const rightAttInfo = getAttentionInfo(focusAtt, heads, "right", token); this.vizs.leftHeads.options.offset = this.uiConf.offset this.vizs.leftHeads.update(leftAttInfo) this.vizs.rightHeads.update(rightAttInfo) this._renderHeadSummary(); // Make sure heads.forEach((h) => { if (this.uiConf.headSet().has(h)) { selectHead(h) } else { unselectHead(h) } }) }; renderTokens() { const left = this.tokCapsule[this.uiConf.attType[0]] const right = this.tokCapsule[this.uiConf.attType[1]] console.log("now: ", this.uiConf.offset); this.vizs.tokens.left.options.offset = this.uiConf.offset this.vizs.tokens.left.update(left.tokenData); this.vizs.tokens.left.mask(left.maskInds); this.vizs.tokens.right.update(right.tokenData); this.vizs.tokens.right.mask(right.maskInds); // displaySelectedToken } renderSvg() { const att = this.attCapsule.byHeads(this.uiConf.heads()) this.vizs.attentionSvg.options.offset = this.uiConf.offset const svg = <AttentionGraph>this.vizs.attentionSvg.data(att); svg.update(att) const maxTokens = _.max([this.tokCapsule.a.length()]) const newHeight = svg.options.boxheight * maxTokens svg.height(newHeight) // Don't redisplay everything if one token is selected showBySide(this.uiConf.token()) }; render() { this.renderTokens(); this.renderSvg(); this.renderAttHead(); } update() { this.render(); } }
the_stack
import { kea } from 'kea' import { router } from 'kea-router' import { identifierToHuman, setPageTitle } from 'lib/utils' import posthog from 'posthog-js' import { sceneLogicType } from './sceneLogicType' import { eventUsageLogic } from 'lib/utils/eventUsageLogic' import { preflightLogic } from './PreflightCheck/logic' import { AvailableFeature } from '~/types' import { userLogic } from './userLogic' import { afterLoginRedirect } from './authentication/loginLogic' import { teamLogic } from './teamLogic' import { urls } from 'scenes/urls' import { SceneExport, Params, Scene, SceneConfig, SceneParams, LoadedScene } from 'scenes/sceneTypes' import { emptySceneParams, preloadedScenes, redirects, routes, sceneConfigurations } from 'scenes/scenes' import { organizationLogic } from './organizationLogic' /** Mapping of some scenes that aren't directly accessible from the sidebar to ones that are - for the sidebar. */ const sceneNavAlias: Partial<Record<Scene, Scene>> = { [Scene.InsightRouter]: Scene.Insight, [Scene.Action]: Scene.Events, [Scene.Actions]: Scene.Events, [Scene.EventStats]: Scene.Events, [Scene.EventPropertyStats]: Scene.Events, [Scene.Person]: Scene.Persons, [Scene.Groups]: Scene.Persons, [Scene.Group]: Scene.Persons, [Scene.Dashboard]: Scene.Dashboards, [Scene.FeatureFlag]: Scene.FeatureFlags, } export const sceneLogic = kea<sceneLogicType>({ props: {} as { scenes?: Record<Scene, () => any> }, path: ['scenes', 'sceneLogic'], actions: { /* 1. Prepares to open the scene, as the listener may override and do something else (e.g. redirecting if unauthenticated), then calls (2) `loadScene`*/ openScene: (scene: Scene, params: SceneParams, method: string) => ({ scene, params, method }), // 2. Start loading the scene's Javascript and mount any logic, then calls (3) `setScene` loadScene: (scene: Scene, params: SceneParams, method: string) => ({ scene, params, method }), // 3. Set the `scene` reducer setScene: (scene: Scene, params: SceneParams, scrollToTop: boolean = false) => ({ scene, params, scrollToTop }), setLoadedScene: (loadedScene: LoadedScene) => ({ loadedScene, }), showUpgradeModal: (featureName: string, featureCaption: string) => ({ featureName, featureCaption }), guardAvailableFeature: ( featureKey: AvailableFeature, featureName: string, featureCaption: string, featureAvailableCallback?: () => void, guardOn: { cloud: boolean selfHosted: boolean } = { cloud: true, selfHosted: true, } ) => ({ featureKey, featureName, featureCaption, featureAvailableCallback, guardOn }), hideUpgradeModal: true, takeToPricing: true, reloadBrowserDueToImportError: true, }, reducers: { scene: [ null as Scene | null, { setScene: (_, payload) => payload.scene, }, ], loadedScenes: [ preloadedScenes, { setScene: (state, { scene, params }) => scene in state ? { ...state, [scene]: { ...state[scene], sceneParams: params, lastTouch: new Date().valueOf() }, } : state, setLoadedScene: (state, { loadedScene }) => ({ ...state, [loadedScene.name]: { ...loadedScene, lastTouch: new Date().valueOf() }, }), }, ], loadingScene: [ null as Scene | null, { loadScene: (_, { scene }) => scene, setScene: () => null, }, ], upgradeModalFeatureNameAndCaption: [ null as [string, string] | null, { showUpgradeModal: (_, { featureName, featureCaption }) => [featureName, featureCaption], hideUpgradeModal: () => null, takeToPricing: () => null, }, ], lastReloadAt: [ null as number | null, { persist: true }, { reloadBrowserDueToImportError: () => new Date().valueOf(), }, ], }, selectors: { sceneConfig: [ (s) => [s.scene], (scene: Scene): SceneConfig | null => { return sceneConfigurations[scene] || null }, ], activeScene: [ (s) => [s.scene, teamLogic.selectors.isCurrentTeamUnavailable], (scene, isCurrentTeamUnavailable) => { return isCurrentTeamUnavailable && scene && sceneConfigurations[scene]?.projectBased ? Scene.ErrorProjectUnavailable : scene }, ], aliasedActiveScene: [ (s) => [s.activeScene], (activeScene) => (activeScene ? sceneNavAlias[activeScene] || activeScene : null), ], activeLoadedScene: [ (s) => [s.activeScene, s.loadedScenes], (activeScene, loadedScenes) => (activeScene ? loadedScenes[activeScene] : null), ], sceneParams: [ (s) => [s.activeLoadedScene], (activeLoadedScene): SceneParams => activeLoadedScene?.sceneParams || { params: {}, searchParams: {}, hashParams: {} }, ], activeSceneLogic: [ (s) => [s.activeLoadedScene, s.sceneParams], (activeLoadedScene, sceneParams) => activeLoadedScene?.logic ? activeLoadedScene.logic.build(activeLoadedScene.paramsToProps?.(sceneParams) || {}, false) : null, ], params: [(s) => [s.sceneParams], (sceneParams): Record<string, string> => sceneParams.params || {}], searchParams: [(s) => [s.sceneParams], (sceneParams): Record<string, any> => sceneParams.searchParams || {}], hashParams: [(s) => [s.sceneParams], (sceneParams): Record<string, any> => sceneParams.hashParams || {}], }, urlToAction: ({ actions }) => { const mapping: Record< string, ( params: Params, searchParams: Params, hashParams: Params, payload: { method: string } ) => any > = {} for (const path of Object.keys(redirects)) { mapping[path] = (params) => { const redirect = redirects[path] router.actions.replace(typeof redirect === 'function' ? redirect(params) : redirect) } } for (const [path, scene] of Object.entries(routes)) { mapping[path] = (params, searchParams, hashParams, { method }) => actions.openScene(scene, { params, searchParams, hashParams }, method) } mapping['/*'] = (_, __, { method }) => actions.loadScene(Scene.Error404, emptySceneParams, method) return mapping }, listeners: ({ values, actions, props, selectors }) => ({ showUpgradeModal: ({ featureName }) => { eventUsageLogic.actions.reportUpgradeModalShown(featureName) }, guardAvailableFeature: ({ featureKey, featureName, featureCaption, featureAvailableCallback, guardOn }) => { const { preflight } = preflightLogic.values let featureAvailable: boolean if (!preflight) { featureAvailable = false } else if (!guardOn.cloud && preflight.cloud) { featureAvailable = true } else if (!guardOn.selfHosted && !preflight.cloud) { featureAvailable = true } else { featureAvailable = userLogic.values.hasAvailableFeature(featureKey) } if (featureAvailable) { featureAvailableCallback?.() } else { actions.showUpgradeModal(featureName, featureCaption) } }, takeToPricing: () => { posthog.capture('upgrade modal pricing interaction') if (preflightLogic.values.preflight?.cloud) { return router.actions.push('/organization/billing') } const pricingTab = preflightLogic.values.preflight?.cloud ? 'cloud' : 'vpc' window.open(`https://posthog.com/pricing?o=${pricingTab}`) }, setScene: ({ scene, scrollToTop }, _, __, previousState) => { posthog.capture('$pageview') setPageTitle(sceneConfigurations[scene]?.name || identifierToHuman(scene || '')) // if we clicked on a link, scroll to top const previousScene = selectors.scene(previousState) if (scrollToTop && scene !== previousScene) { window.scrollTo(0, 0) } }, openScene: ({ scene, params, method }) => { const sceneConfig = sceneConfigurations[scene] || {} const { user } = userLogic.values const { preflight } = preflightLogic.values if (scene === Scene.Signup && preflight && !preflight.can_create_org) { // If user is on an already initiated self-hosted instance, redirect away from signup router.actions.replace(urls.login()) return } if (user) { // If user is already logged in, redirect away from unauthenticated-only routes (e.g. /signup) if (sceneConfig.onlyUnauthenticated) { if (scene === Scene.Login) { router.actions.replace(afterLoginRedirect()) } else { router.actions.replace(urls.default()) } return } // Redirect to org/project creation if there's no org/project respectively, unless using invite if (scene !== Scene.InviteSignup) { if (organizationLogic.values.isCurrentOrganizationUnavailable) { if (location.pathname !== urls.organizationCreateFirst()) { console.log('Organization not available, redirecting to organization creation') router.actions.replace(urls.organizationCreateFirst()) return } } else if (teamLogic.values.isCurrentTeamUnavailable) { if (location.pathname !== urls.projectCreateFirst()) { console.log('Organization not available, redirecting to project creation') router.actions.replace(urls.projectCreateFirst()) return } } else if ( teamLogic.values.currentTeam && !teamLogic.values.currentTeam.completed_snippet_onboarding && !location.pathname.startsWith('/ingestion') && !location.pathname.startsWith('/personalization') ) { console.log('Ingestion tutorial not completed, redirecting to it') router.actions.replace(urls.ingestion()) return } } } actions.loadScene(scene, params, method) }, loadScene: async ({ scene, params, method }, breakpoint) => { const clickedLink = method === 'PUSH' if (values.scene === scene) { actions.setScene(scene, params, clickedLink) return } if (!props.scenes?.[scene]) { actions.setScene(Scene.Error404, emptySceneParams, clickedLink) return } let loadedScene = values.loadedScenes[scene] const wasNotLoaded = !loadedScene if (!loadedScene) { // if we can't load the scene in a second, show a spinner const timeout = window.setTimeout(() => actions.setScene(scene, params, true), 500) let importedScene try { window.ESBUILD_LOAD_CHUNKS?.(scene) importedScene = await props.scenes[scene]() } catch (error) { if ( error.name === 'ChunkLoadError' || // webpack error.message?.includes('Failed to fetch dynamically imported module') // esbuild ) { // Reloaded once in the last 20 seconds and now reloading again? Show network error if ( values.lastReloadAt && parseInt(String(values.lastReloadAt)) > new Date().valueOf() - 20000 ) { console.error('App assets regenerated. Showing error page.') actions.setScene(Scene.ErrorNetwork, emptySceneParams, clickedLink) } else { console.error('App assets regenerated. Reloading this page.') actions.reloadBrowserDueToImportError() } return } else { throw error } } finally { window.clearTimeout(timeout) } breakpoint() const { default: defaultExport, logic, scene: _scene, ...others } = importedScene if (_scene) { loadedScene = { name: scene, ...(_scene as SceneExport), sceneParams: params } } else if (defaultExport) { console.warn(`Scene ${scene} not yet converted to use SceneExport!`) loadedScene = { name: scene, component: defaultExport, logic: logic, sceneParams: params, } } else { console.warn(`Scene ${scene} not yet converted to use SceneExport!`) loadedScene = { name: scene, component: Object.keys(others).length === 1 ? others[Object.keys(others)[0]] : values.loadedScenes[Scene.Error404].component, logic: logic, sceneParams: params, } if (Object.keys(others).length > 1) { console.error('There are multiple exports for this scene. Showing 404 instead.') } } actions.setLoadedScene(loadedScene) if (loadedScene.logic) { // initialize the logic and give it 50ms to load before opening the scene const unmount = loadedScene.logic.build(loadedScene.paramsToProps?.(params) || {}, false).mount() try { await breakpoint(50) } catch (e) { // if we change the scene while waiting these 50ms, unmount unmount() throw e } } } actions.setScene(scene, params, clickedLink || wasNotLoaded) }, reloadBrowserDueToImportError: () => { window.location.reload() }, }), })
the_stack
declare module 'perf_hooks' { import { AsyncResource } from 'node:async_hooks'; type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; interface NodeGCPerformanceDetail { /** * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies * the type of garbage collection operation that occurred. * See perf_hooks.constants for valid values. */ readonly kind?: number | undefined; /** * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` * property contains additional information about garbage collection operation. * See perf_hooks.constants for valid values. */ readonly flags?: number | undefined; } /** * @since v8.5.0 */ class PerformanceEntry { protected constructor(); /** * The total number of milliseconds elapsed for this entry. This value will not * be meaningful for all Performance Entry types. * @since v8.5.0 */ readonly duration: number; /** * The name of the performance entry. * @since v8.5.0 */ readonly name: string; /** * The high resolution millisecond timestamp marking the starting time of the * Performance Entry. * @since v8.5.0 */ readonly startTime: number; /** * The type of the performance entry. It may be one of: * * * `'node'` (Node.js only) * * `'mark'` (available on the Web) * * `'measure'` (available on the Web) * * `'gc'` (Node.js only) * * `'function'` (Node.js only) * * `'http2'` (Node.js only) * * `'http'` (Node.js only) * @since v8.5.0 */ readonly entryType: EntryType; /** * Additional detail specific to the `entryType`. * @since v16.0.0 */ readonly details?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. } /** * _This property is an extension by Node.js. It is not available in Web browsers._ * * Provides timing details for Node.js itself. The constructor of this class * is not exposed to users. * @since v8.5.0 */ class PerformanceNodeTiming extends PerformanceEntry { /** * The high resolution millisecond timestamp at which the Node.js process * completed bootstrapping. If bootstrapping has not yet finished, the property * has the value of -1. * @since v8.5.0 */ readonly bootstrapComplete: number; /** * The high resolution millisecond timestamp at which the Node.js environment was * initialized. * @since v8.5.0 */ readonly environment: number; /** * The high resolution millisecond timestamp of the amount of time the event loop * has been idle within the event loop's event provider (e.g. `epoll_wait`). This * does not take CPU usage into consideration. If the event loop has not yet * started (e.g., in the first tick of the main script), the property has the * value of 0. * @since v14.10.0, v12.19.0 */ readonly idleTime: number; /** * The high resolution millisecond timestamp at which the Node.js event loop * exited. If the event loop has not yet exited, the property has the value of -1\. * It can only have a value of not -1 in a handler of the `'exit'` event. * @since v8.5.0 */ readonly loopExit: number; /** * The high resolution millisecond timestamp at which the Node.js event loop * started. If the event loop has not yet started (e.g., in the first tick of the * main script), the property has the value of -1. * @since v8.5.0 */ readonly loopStart: number; /** * The high resolution millisecond timestamp at which the V8 platform was * initialized. * @since v8.5.0 */ readonly v8Start: number; } interface EventLoopUtilization { idle: number; active: number; utilization: number; } /** * @param util1 The result of a previous call to eventLoopUtilization() * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 */ type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: EventLoopUtilization) => EventLoopUtilization; interface MarkOptions { /** * Additional optional detail to include with the mark. */ detail?: unknown | undefined; /** * An optional timestamp to be used as the mark time. * @default `performance.now()`. */ startTime?: number | undefined; } interface MeasureOptions { /** * Additional optional detail to include with the mark. */ detail?: unknown | undefined; /** * Duration between start and end times. */ duration?: number | undefined; /** * Timestamp to be used as the end time, or a string identifying a previously recorded mark. */ end?: number | string | undefined; /** * Timestamp to be used as the start time, or a string identifying a previously recorded mark. */ start?: number | string | undefined; } interface TimerifyOptions { /** * A histogram object created using * `perf_hooks.createHistogram()` that will record runtime durations in * nanoseconds. */ histogram?: RecordableHistogram | undefined; } interface Performance { /** * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. * If name is provided, removes only the named mark. * @param name */ clearMarks(name?: string): void; /** * Creates a new PerformanceMark entry in the Performance Timeline. * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', * and whose performanceEntry.duration is always 0. * Performance marks are used to mark specific significant moments in the Performance Timeline. * @param name */ mark(name?: string, options?: MarkOptions): void; /** * Creates a new PerformanceMeasure entry in the Performance Timeline. * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. * * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, * then startMark is set to timeOrigin by default. * * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. * @param name * @param startMark * @param endMark */ measure(name: string, startMark?: string, endMark?: string): void; measure(name: string, options: MeasureOptions): void; /** * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. */ readonly nodeTiming: PerformanceNodeTiming; /** * @return the current high resolution millisecond timestamp */ now(): number; /** * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. */ readonly timeOrigin: number; /** * Wraps a function within a new function that measures the running time of the wrapped function. * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. * @param fn */ timerify<T extends (...params: any[]) => any>(fn: T, options?: TimerifyOptions): T; /** * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). * No other CPU idle time is taken into consideration. */ eventLoopUtilization: EventLoopUtilityFunction; } interface PerformanceObserverEntryList { /** * Returns a list of `PerformanceEntry` objects in chronological order * with respect to `performanceEntry.startTime`. * * ```js * const { * performance, * PerformanceObserver * } = require('perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntries()); * * * [ * * PerformanceEntry { * * name: 'test', * * entryType: 'mark', * * startTime: 81.465639, * * duration: 0 * * }, * * PerformanceEntry { * * name: 'meow', * * entryType: 'mark', * * startTime: 81.860064, * * duration: 0 * * } * * ] * * observer.disconnect(); * }); * obs.observe({ type: 'mark' }); * * performance.mark('test'); * performance.mark('meow'); * ``` * @since v8.5.0 */ getEntries(): PerformanceEntry[]; /** * Returns a list of `PerformanceEntry` objects in chronological order * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. * * ```js * const { * performance, * PerformanceObserver * } = require('perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntriesByName('meow')); * * * [ * * PerformanceEntry { * * name: 'meow', * * entryType: 'mark', * * startTime: 98.545991, * * duration: 0 * * } * * ] * * console.log(perfObserverList.getEntriesByName('nope')); // [] * * console.log(perfObserverList.getEntriesByName('test', 'mark')); * * * [ * * PerformanceEntry { * * name: 'test', * * entryType: 'mark', * * startTime: 63.518931, * * duration: 0 * * } * * ] * * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] * observer.disconnect(); * }); * obs.observe({ entryTypes: ['mark', 'measure'] }); * * performance.mark('test'); * performance.mark('meow'); * ``` * @since v8.5.0 */ getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; /** * Returns a list of `PerformanceEntry` objects in chronological order * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. * * ```js * const { * performance, * PerformanceObserver * } = require('perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntriesByType('mark')); * * * [ * * PerformanceEntry { * * name: 'test', * * entryType: 'mark', * * startTime: 55.897834, * * duration: 0 * * }, * * PerformanceEntry { * * name: 'meow', * * entryType: 'mark', * * startTime: 56.350146, * * duration: 0 * * } * * ] * * observer.disconnect(); * }); * obs.observe({ type: 'mark' }); * * performance.mark('test'); * performance.mark('meow'); * ``` * @since v8.5.0 */ getEntriesByType(type: EntryType): PerformanceEntry[]; } type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; class PerformanceObserver extends AsyncResource { constructor(callback: PerformanceObserverCallback); /** * Disconnects the `PerformanceObserver` instance from all notifications. * @since v8.5.0 */ disconnect(): void; /** * Subscribes the `<PerformanceObserver>` instance to notifications of new `<PerformanceEntry>` instances identified either by `options.entryTypes`or `options.type`: * * ```js * const { * performance, * PerformanceObserver * } = require('perf_hooks'); * * const obs = new PerformanceObserver((list, observer) => { * // Called three times synchronously. `list` contains one item. * }); * obs.observe({ type: 'mark' }); * * for (let n = 0; n < 3; n++) * performance.mark(`test${n}`); * ``` * @since v8.5.0 */ observe( options: | { entryTypes: ReadonlyArray<EntryType>; } | { type: EntryType; } ): void; } namespace constants { const NODE_PERFORMANCE_GC_MAJOR: number; const NODE_PERFORMANCE_GC_MINOR: number; const NODE_PERFORMANCE_GC_INCREMENTAL: number; const NODE_PERFORMANCE_GC_WEAKCB: number; const NODE_PERFORMANCE_GC_FLAGS_NO: number; const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; } const performance: Performance; interface EventLoopMonitorOptions { /** * The sampling rate in milliseconds. * Must be greater than zero. * @default 10 */ resolution?: number | undefined; } interface Histogram { /** * Returns a `Map` object detailing the accumulated percentile distribution. * @since v11.10.0 */ readonly percentiles: Map<number, number>; /** * The number of times the event loop delay exceeded the maximum 1 hour event * loop delay threshold. * @since v11.10.0 */ readonly exceeds: number; /** * The minimum recorded event loop delay. * @since v11.10.0 */ readonly min: number; /** * The maximum recorded event loop delay. * @since v11.10.0 */ readonly max: number; /** * The mean of the recorded event loop delays. * @since v11.10.0 */ readonly mean: number; /** * The standard deviation of the recorded event loop delays. * @since v11.10.0 */ readonly stddev: number; /** * Resets the collected histogram data. * @since v11.10.0 */ reset(): void; /** * Returns the value at the given percentile. * @since v11.10.0 * @param percentile A percentile value in the range (0, 100]. */ percentile(percentile: number): number; } interface IntervalHistogram extends Histogram { /** * Enables the update interval timer. Returns `true` if the timer was * started, `false` if it was already started. * @since v11.10.0 */ enable(): boolean; /** * Disables the update interval timer. Returns `true` if the timer was * stopped, `false` if it was already stopped. * @since v11.10.0 */ disable(): boolean; } interface RecordableHistogram extends Histogram { /** * @since v15.9.0 * @param val The amount to record in the histogram. */ record(val: number | bigint): void; /** * Calculates the amount of time (in nanoseconds) that has passed since the * previous call to `recordDelta()` and records that amount in the histogram. * * ## Examples * @since v15.9.0 */ recordDelta(): void; } /** * _This property is an extension by Node.js. It is not available in Web browsers._ * * Creates an `IntervalHistogram` object that samples and reports the event loop * delay over time. The delays will be reported in nanoseconds. * * Using a timer to detect approximate event loop delay works because the * execution of timers is tied specifically to the lifecycle of the libuv * event loop. That is, a delay in the loop will cause a delay in the execution * of the timer, and those delays are specifically what this API is intended to * detect. * * ```js * const { monitorEventLoopDelay } = require('perf_hooks'); * const h = monitorEventLoopDelay({ resolution: 20 }); * h.enable(); * // Do something. * h.disable(); * console.log(h.min); * console.log(h.max); * console.log(h.mean); * console.log(h.stddev); * console.log(h.percentiles); * console.log(h.percentile(50)); * console.log(h.percentile(99)); * ``` * @since v11.10.0 */ function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; interface CreateHistogramOptions { /** * The minimum recordable value. Must be an integer value greater than 0. * @default 1 */ min?: number | bigint | undefined; /** * The maximum recordable value. Must be an integer value greater than min. * @default Number.MAX_SAFE_INTEGER */ max?: number | bigint | undefined; /** * The number of accuracy digits. Must be a number between 1 and 5. * @default 3 */ figures?: number | undefined; } /** * Returns a `<RecordableHistogram>`. * @since v15.9.0 */ function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; } declare module 'node:perf_hooks' { export * from 'perf_hooks'; }
the_stack
import { css } from '@emotion/react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import classnames from 'classnames'; import cloneDeep from 'lodash.clonedeep'; import now from 'lodash.now'; import React from 'react'; import { Edge, EdgeChildProps, } from 'reaflow'; import { SetterOrUpdater, useRecoilState, useSetRecoilState, } from 'recoil'; import { absoluteLabelEditorState } from '../../states/absoluteLabelEditorStateState'; import { blockPickerMenuSelector } from '../../states/blockPickerMenuState'; import { canvasDatasetSelector } from '../../states/canvasDatasetSelector'; import { edgesSelector } from '../../states/edgesState'; import { lastCreatedState } from '../../states/lastCreatedState'; import { selectedEdgesSelector } from '../../states/selectedEdgesState'; import { selectedNodesSelector } from '../../states/selectedNodesState'; import BaseEdgeData from '../../types/BaseEdgeData'; import BaseEdgeProps, { PatchCurrentEdge } from '../../types/BaseEdgeProps'; import BaseNodeData from '../../types/BaseNodeData'; import BasePortData from '../../types/BasePortData'; import BlockPickerMenu, { OnBlockClick } from '../../types/BlockPickerMenu'; import { NewCanvasDatasetMutation } from '../../types/CanvasDatasetMutation'; import { LastCreated } from '../../types/LastCreated'; import NodeType from '../../types/NodeType'; import { translateXYToCanvasPosition } from '../../utils/canvas'; import { createNodeFromDefaultProps, getDefaultNodePropsWithFallback, upsertNodeThroughPorts, } from '../../utils/nodes'; import Label from './Label'; type Props = {} & BaseEdgeProps; /** * Base edge component. * * This component contains shared business logic common to all edges. * It renders a Reaflow <Edge> component. * * The Edge renders itself as SVG <g> HTML element wrapper, which contains the <path> HTML element that displays the link itself. * * @see https://reaflow.dev/?path=/story/demos-edges */ const BaseEdge: React.FunctionComponent<Props> = (props) => { const { id, source: sourceNodeId, sourcePort: sourcePortId, target: targetNodeId, targetPort: targetPortId, queueCanvasDatasetMutation, } = props; // console.log('props', props) const [blockPickerMenu, setBlockPickerMenu] = useRecoilState<BlockPickerMenu>(blockPickerMenuSelector); const [canvasDataset, setCanvasDataset] = useRecoilState(canvasDatasetSelector); const [edges, setEdges] = useRecoilState(edgesSelector); const { nodes } = canvasDataset; const setLastCreatedNode: SetterOrUpdater<LastCreated | undefined> = useSetRecoilState(lastCreatedState); const { displayedFrom, isDisplayed } = blockPickerMenu; const edge: BaseEdgeData = edges.find((edge: BaseEdgeData) => edge?.id === id) as BaseEdgeData; const [selectedEdges, setSelectedEdges] = useRecoilState(selectedEdgesSelector); const [selectedNodes, setSelectedNodes] = useRecoilState(selectedNodesSelector); const setAbsoluteLabelEditor = useSetRecoilState(absoluteLabelEditorState); if (typeof edge === 'undefined') { return null; } // Resolve instances of connected nodes and ports const sourceNode: BaseNodeData | undefined = nodes.find((node: BaseNodeData) => node.id === sourceNodeId); const sourcePort: BasePortData | undefined = sourceNode?.ports?.find((port: BasePortData) => port.id === sourcePortId); const targetNode: BaseNodeData | undefined = nodes.find((node: BaseNodeData) => node.id === targetNodeId); const targetPort: BasePortData | undefined = targetNode?.ports?.find((port: BasePortData) => port.id === targetPortId); const isSelected = !!selectedEdges?.find((selectedEdge: string) => selectedEdge === edge.id); // console.log('edgeProps', props); /** * Invoked when clicking on the "+" of the edge. * * Displays the BlockPickerMenu, which can then be used to select which Block to add to the canvas. * If the BlockPickerMenu was already displayed, hides it if it was opened from the same edge. * * When a block is clicked, the "onBlockClick" function is invoked and creates (upserts) the node * by splitting the edge in two parts and adding the new node in between. * * @param event */ const onAddIconClick = (event: React.MouseEvent<SVGGElement, MouseEvent>): void => { /** * Executed when clicking on a block. * Creates a new node corresponding to the selected block. * * @param nodeType */ const onBlockClick: OnBlockClick = (nodeType: NodeType) => { console.groupCollapsed('Clicked on block from edge, upserting new node'); const newNode: BaseNodeData = createNodeFromDefaultProps(getDefaultNodePropsWithFallback(nodeType)); const mutations: NewCanvasDatasetMutation[] = upsertNodeThroughPorts(cloneDeep(nodes), cloneDeep(edges), edge, newNode); // Apply all mutations mutations.map((mutation) => queueCanvasDatasetMutation(mutation)); setLastCreatedNode({ node: newNode, at: now() }); setSelectedNodes([newNode?.id]); setSelectedEdges([]); console.groupEnd(); }; // Converts the x/y position to a Canvas position and apply some margin for the BlockPickerMenu to display on the right bottom of the cursor const [x, y] = translateXYToCanvasPosition(event.clientX, event.clientY, { left: 15, top: 15 }); setBlockPickerMenu({ displayedFrom: `edge-${edge.id}`, // Toggles on click if the source is the same, otherwise update isDisplayed: displayedFrom === `edge-${edge.id}` ? !isDisplayed : true, onBlockClick, eventTarget: event.target, top: y, left: x, }); }; /** * Invoked when clicking on the "-" of the edge. * * Removes the selected edge. * * @param event */ const onRemoveIconClick = (event: React.MouseEvent<SVGGElement, MouseEvent>): void => { console.log('onRemoveIconClick', event, edge); const mutation: NewCanvasDatasetMutation = { operationType: 'delete', elementId: edge?.id, elementType: 'edge', }; console.log('Adding edge patch to the queue', 'mutation:', mutation); queueCanvasDatasetMutation(mutation); }; /** * Selects the edge when clicking on it. * * XXX We're resolving the "edge" ourselves, instead of relying on the 2nd argument (edgeData), * which doesn't contain all the expected properties. It is more reliable to use the current edge, which already known. * * @param event * @param data_DO_NOT_USE */ const onEdgeClick = (event: React.MouseEvent<SVGGElement, MouseEvent>, data_DO_NOT_USE: BaseEdgeData) => { console.log('onEdgeClick', event, edge); setSelectedEdges([edge.id]); }; /** * Patches the properties of the current edge. * * Only updates the provided properties, doesn't update other properties. * Will use deep merge of properties. * * @param patch * @param stateUpdateDelay */ const patchCurrentEdge: PatchCurrentEdge = (patch: Partial<BaseEdgeData>, stateUpdateDelay = 0): void => { const mutation: NewCanvasDatasetMutation = { operationType: 'patch', elementId: edge?.id, elementType: 'edge', changes: patch, }; console.log('Adding edge patch to the queue', 'patch:', patch, 'mutation:', mutation); queueCanvasDatasetMutation(mutation, stateUpdateDelay); }; return ( <Edge {...props} label={<Label />} className={classnames(`edge-svg-graph`, { 'is-selected': isSelected })} onClick={onEdgeClick} > { (edgeChildProps: EdgeChildProps) => { const { center, } = edgeChildProps; // Improve centering (because we have 3 icons), and position the foreignObject children above the line const x = (center?.x || 0) - 25; const y = (center?.y || 0) - 25; /** * Triggered when the label has been modified. * * @param value */ const onLabelSubmit = (value: string) => { console.log('value', value); patchCurrentEdge({ text: value || ' ', // Use a space as default, to increase the distance between nodes, which ease edge's selection }); }; const onStartLabelEditing = (event: React.MouseEvent<SVGGElement, MouseEvent>) => { setAbsoluteLabelEditor({ x: window.innerWidth / 2, y: 0, defaultValue: edge?.text, onSubmit: onLabelSubmit, isDisplayed: true, }); }; return ( <foreignObject id={`edge-foreignObject-${edge.id}`} className={classnames(`edge-container`, { 'is-selected': isSelected, })} width={100} // Content width will be limited by the width of the foreignObject height={60} x={x} y={y} css={css` position: relative; color: black; z-index: 1; // Disabling pointer-events on top-level container, because the foreignObject is displayed on top (above) the edge line itself and blocks selection pointer-events: none; .edge { // XXX Elements within a <foreignObject> that are using the CSS "position" attribute won't be shown properly, // unless they're wrapped into a container using a "fixed" position. // Solves the display of React Select element. // See https://github.com/chakra-ui/chakra-ui/issues/3288#issuecomment-776316200 position: fixed; // Enable pointer events for elements within the edge pointer-events: auto; } .svg-inline--fa { cursor: pointer; margin: 4px; } `} > { isSelected && ( <div className={'edge'}> <FontAwesomeIcon color={'#0028FF'} icon={['fas', 'plus-circle']} onClick={onAddIconClick} /> <FontAwesomeIcon color={'#F9694A'} icon={['fas', 'times-circle']} onClick={onRemoveIconClick} /> <FontAwesomeIcon icon={['fas', 'edit']} onClick={onStartLabelEditing} /> </div> ) } </foreignObject> ); } } </Edge> ); }; export default BaseEdge;
the_stack
import { createModel } from '@rematch/core'; import { message } from 'antd'; import intl from 'react-intl-universal'; import service from '#assets/config/service'; import { configToJson, getGQLByConfig } from '#assets/utils/import'; interface ITag { props: any[]; name: string; } interface IVertexConfig { name: string; file: any; tags: ITag[]; idMapping: any; } interface IEdgeConfig { name: string; file: any; props: any[]; type: string; } interface IState { currentStep: number; activeStep: number; mountPath: string; files: any[]; vertexesConfig: IVertexConfig[]; edgesConfig: IEdgeConfig[]; activeVertexIndex: number; activeEdgeIndex: number; vertexAddCount: number; edgeAddCount: number; isImporting: boolean; taskId: string; } export const importData = createModel({ state: { activeStep: 0, currentStep: 0, // the mountPath config by the env variable of WORKING_DIR, upload file must be in that dir. mountPath: '', files: [] as any[], vertexesConfig: [] as IVertexConfig[], edgesConfig: [] as IEdgeConfig[], activeVertexIndex: -1, activeEdgeIndex: -1, isImporting: false, taskId: 'all', vertexAddCount: 1, edgeAddCount: 1, }, reducers: { update: (state: IState, payload: any) => { return { ...state, ...payload, }; }, newVertexConfig: (state: IState, payload: any) => { const { file } = payload; const { vertexesConfig, vertexAddCount } = state; const vertexName = `${intl.get('import.datasource')} ${vertexAddCount}`; return { ...state, vertexesConfig: [ ...vertexesConfig, { name: vertexName, file, tags: [], idMapping: null, }, ], activeVertexIndex: vertexesConfig.length, vertexAddCount: vertexAddCount + 1, }; }, updateVertexConfig: (state: IState, vertex: IVertexConfig) => { const { activeVertexIndex, vertexesConfig } = state; vertexesConfig[activeVertexIndex] = vertex; return { ...state, vertexesConfig, }; }, deleteVertexConfig: (state: IState, payload: any) => { const { vertexName } = payload; const { vertexesConfig, activeVertexIndex } = state; let deleteIndex; const newVertexesConfig = vertexesConfig.filter((v, i) => { if (v.name !== vertexName) { return true; } else { deleteIndex = i; return false; } }); let newActiveVertexIndex; if (activeVertexIndex === deleteIndex) { newActiveVertexIndex = newVertexesConfig.length === 0 ? -1 : 0; } else { newActiveVertexIndex = activeVertexIndex > deleteIndex ? activeVertexIndex - 1 : activeVertexIndex; } return { ...state, activeVertexIndex: newActiveVertexIndex, vertexesConfig: newVertexesConfig, }; }, updateTagConfig: ( state: IState, payload: { tagIndex: number; props: any; tag: string; }, ) => { const { vertexesConfig, activeVertexIndex } = state; const vertex = vertexesConfig[activeVertexIndex]; const { props, tagIndex, tag } = payload; const tagConfig = vertex.tags[tagIndex]; tagConfig.name = tag; tagConfig.props = props; return { ...state, vertexesConfig, }; }, deleteTag: (state: IState, tagIndex: number) => { const { vertexesConfig, activeVertexIndex } = state; const vertex = vertexesConfig[activeVertexIndex]; vertex.tags.splice(tagIndex, 1); return { ...state, vertexesConfig: [...vertexesConfig], }; }, addTag: (state: IState) => { const { vertexesConfig, activeVertexIndex } = state; const vertex = vertexesConfig[activeVertexIndex]; vertex.tags.push({ name: '', props: [], }); return { ...state, vertexesConfig: [...vertexesConfig], }; }, newEdgeConfig: (state: IState, payload: any) => { const { file } = payload; const { edgesConfig, edgeAddCount } = state; const edgeName = `Edge ${edgeAddCount}`; return { ...state, edgesConfig: [ ...edgesConfig, { file, name: edgeName, props: [], type: '', }, ], activeEdgeIndex: edgesConfig.length, edgeAddCount: edgeAddCount + 1, }; }, deleteEdgeConfig: (state: IState, payload: any) => { const { edgesConfig, activeEdgeIndex } = state; const { edgeName } = payload; let deleteIndex; const newEdgesConfig = edgesConfig.filter((e, i) => { if (e.name !== edgeName) { return true; } else { deleteIndex = i; return false; } }); let newActiveEdgeIndex; if (activeEdgeIndex === deleteIndex) { newActiveEdgeIndex = newEdgesConfig.length === 0 ? -1 : 0; } else { newActiveEdgeIndex = activeEdgeIndex > deleteIndex ? activeEdgeIndex - 1 : activeEdgeIndex; } return { ...state, edgesConfig: newEdgesConfig, activeEdgeIndex: newActiveEdgeIndex, }; }, updateEdgeConfig: (state: IState, payload: any) => { const { edgesConfig, activeEdgeIndex } = state; const { props, edgeType } = payload; const edge = edgesConfig[activeEdgeIndex]; edge.props = props; edge.type = edgeType; return { ...state, edgesConfig, }; }, // just make new copy config to render refresh: (state: IState) => { return { ...state, }; }, nextStep: (state: IState) => { const { activeStep, currentStep } = state; switch (activeStep) { case 0: return { ...state, activeStep: 1, currentStep: currentStep > 1 ? currentStep : 1, }; case 1: return { ...state, currentStep: currentStep > 2 ? currentStep : 2, activeStep: 2, }; case 2: return { ...state, currentStep: currentStep > 3 ? currentStep : 3, activeStep: 3, }; case 3: return { ...state, currentStep: currentStep > 4 ? currentStep : 4, activeStep: 4, }; case 4: return { ...state, activeStep: 0, }; default: return state; } }, }, effects: { async resetAllConfig() { this.update({ activeStep: 0, currentStep: 0, files: [] as any[], vertexesConfig: [] as IVertexConfig[], edgesConfig: [] as IEdgeConfig[], activeVertexIndex: -1, activeEdgeIndex: -1, vertexAddCount: 0, edgeAddCount: 0, isImporting: false, }); }, async importData(payload, rootState) { const { nebula: { spaceVidType }, } = rootState; const config: any = configToJson({ ...payload, spaceVidType }); const { code, data, message } = (await service.importData({ configBody: config, configPath: '', })) as any; if (code === 0) { this.update({ taskId: data[0], isImporting: true, }); } else { message.error(message); } return code; }, async checkImportStatus(payload) { const res = await service.handleImportAction(payload); return res; }, async stopImport(payload) { this.update({ isImporting: false, }); service.handleImportAction(payload); }, async changeTagType(payload: { activeVertexIndex: number; vertexesConfig: IVertexConfig[]; record: any; tagName: string; type: string; }) { const { activeVertexIndex, vertexesConfig, record, tagName, type, } = payload; vertexesConfig[activeVertexIndex].tags.forEach(tag => { if (tag.name === tagName) { tag.props.forEach(prop => { if (prop.name === record.name) { prop.type = type; } }); } }); this.update({ vertexesConfig, }); }, async changeEdgeFieldType(payload: { edge: IEdgeConfig; propName: string; type: string; }) { const { edge, propName, type } = payload; edge.props.forEach(prop => { if (prop.name === propName) { prop.type = type; } }); this.update({ edge, }); }, async testImport(payload, rootState) { const { nebula: { spaceVidType }, } = rootState; const config: any = configToJson({ ...payload, spaceVidType }); const { taskId, errCode } = (await service.importData(config)) as any; this.update({ taskId, }); return errCode; }, async asyncTestDataMapping( payload: { vertexesConfig: any[]; edgesConfig: any[]; activeStep: number; }, rootState, ) { const { vertexesConfig, edgesConfig, activeStep } = payload; const { nebula: { spaceVidType }, } = rootState; const configInfo = { vertexesConfig: activeStep === 2 ? vertexesConfig : [], edgesConfig: activeStep === 3 ? edgesConfig : [], spaceVidType, }; try { const gql: string = getGQLByConfig(configInfo).join(';'); const { code, message: msg } = (await service.execNGQL({ gql, })) as any; if (code !== 0) { message.error(`${msg}`); } return code; } catch (error) { console.log(error); } }, async asyncUpdateEdgeConfig(payload: { edgeType: string }, rootState) { const { edgeType } = payload; const { nebula: { spaceVidType }, } = rootState; const { code, data } = (await service.execNGQL({ gql: 'DESCRIBE EDGE' + '`' + edgeType + '`;', })) as any; const createTag = (await service.execNGQL({ // HACK: Process the default value fields gql: 'show create EDGE' + ' `' + edgeType + '`;', })) as any; const defaultValueFields: any[] = []; if (!!createTag) { const res = (createTag.data.tables && createTag.data.tables[0]['Create Edge']) || ''; // HACK: createTag split to ↵ const fields = res.split(/\n|\r\n/); fields.forEach(field => { const fieldArr = field.trim().split(/\s|\s+/); if (field.includes('default') || fieldArr.includes('DEFAULT')) { let defaultField = fieldArr[0]; if (defaultField.includes('`')) { defaultField = defaultField.replace(/`/g, ''); } defaultValueFields.push(defaultField); } }); } if (code === 0) { const props = data.tables.map(item => { return { name: item.Field, type: item.Type === 'int64' ? 'int' : item.Type, isDefault: defaultValueFields.includes(item.Field), mapping: null, }; }); this.updateEdgeConfig({ props: [ // each edge must have the three special prop srcId, dstId, rank,put them ahead { name: 'srcId', type: spaceVidType === 'INT64' ? 'int' : 'string', mapping: null, }, { name: 'dstId', type: spaceVidType === 'INT64' ? 'int' : 'string', mapping: null, }, { name: 'rank', type: 'int', mapping: null, }, ...props, ], edgeType, }); } }, async asyncUpdateTagConfig(payload: { tag: string; tagIndex: number }) { const { tag, tagIndex } = payload; const { code, data } = (await service.execNGQL({ // HACK: Processing keyword gql: 'DESCRIBE TAG' + ' `' + tag + '`;', })) as any; const createTag = (await service.execNGQL({ // HACK: Process the default value fields gql: 'show create tag' + ' `' + tag + '`;', })) as any; const defaultValueFields: any[] = []; if (!!createTag) { const res = (createTag.data.tables && createTag.data.tables[0]['Create Tag']) || ''; const fields = res.split(/\n|\r\n/); fields.forEach(field => { const fieldArr = field.trim().split(/\s|\s+/); if (fieldArr.includes('default') || fieldArr.includes('DEFAULT')) { let defaultField = fieldArr[0]; if (defaultField.includes('`')) { defaultField = defaultField.replace(/`/g, ''); } defaultValueFields.push(defaultField); } }); } if (code === 0) { const props = data.tables.map(attr => { return { name: attr.Field, type: attr.Type === 'int64' ? 'int' : attr.Type, // HACK: exec return int64 but importer only use int isDefault: defaultValueFields.includes(attr.Field), mapping: null, }; }); this.updateTagConfig({ props, tagIndex, tag, }); } }, async asyncGetImportWorkingDir() { const { code, data } = (await service.getImportWokingDir()) as any; const { dir } = data; if (code === 0 && dir) { this.update({ mountPath: dir.endsWith('/') ? dir.substring(0, dir.length - 1) : dir, }); } else { message.warning(intl.get('import.mountPathWarning'), 5); } }, }, });
the_stack
import { Ray, Vector2 } from "@oasis-engine/math"; import { Canvas } from "../../Canvas"; import { Engine } from "../../Engine"; import { Entity } from "../../Entity"; import { CameraClearFlags } from "../../enums/CameraClearFlags"; import { HitResult } from "../../physics"; import { PointerPhase } from "../enums/PointerPhase"; import { Pointer } from "./Pointer"; /** * Pointer Manager. * @internal */ export class PointerManager { private static _tempRay: Ray = new Ray(); private static _tempPoint: Vector2 = new Vector2(); private static _tempHitResult: HitResult = new HitResult(); /** @internal */ _pointers: Pointer[] = []; /** @internal */ _multiPointerEnabled: boolean = true; /** @internal */ _enablePhysics: boolean = false; private _engine: Engine; private _canvas: Canvas; private _nativeEvents: PointerEvent[] = []; private _pointerPool: Pointer[]; private _keyEventList: number[] = []; private _keyEventCount: number = 0; private _needOverallPointers: boolean = false; private _currentPosition: Vector2 = new Vector2(); private _currentPressedEntity: Entity; private _currentEnteredEntity: Entity; /** * Create a PointerManager. * @param engine - The current engine instance */ constructor(engine: Engine) { this._engine = engine; this._canvas = engine.canvas; // @ts-ignore const htmlCanvas = this._canvas._webCanvas as HTMLCanvasElement; htmlCanvas.style.touchAction = "none"; // prettier-ignore htmlCanvas.onpointerdown = htmlCanvas.onpointerup = htmlCanvas.onpointerout = htmlCanvas.onpointermove = (evt:PointerEvent)=>{ this._nativeEvents.push(evt); }; // If there are no compatibility issues, navigator.maxTouchPoints should be used here. this._pointerPool = new Array<Pointer>(11); this._enablePhysics = engine.physicsManager ? true : false; } /** * @internal */ _update(): void { this._needOverallPointers && this._overallPointers(); this._nativeEvents.length > 0 && this._handlePointerEvent(this._nativeEvents); if (this._enablePhysics) { const rayCastEntity = this._pointerRayCast(); const { _keyEventCount: keyEventCount } = this; if (keyEventCount > 0) { const { _keyEventList: keyEventList } = this; for (let i = 0; i < keyEventCount; i++) { switch (keyEventList[i]) { case PointerKeyEvent.Down: this._firePointerDown(rayCastEntity); break; case PointerKeyEvent.Up: this._firePointerUpAndClick(rayCastEntity); break; } } this._firePointerExitAndEnter(rayCastEntity); keyEventList[keyEventCount - 1] === PointerKeyEvent.Leave && (this._currentPressedEntity = null); this._keyEventCount = 0; } else { this._firePointerDrag(); this._firePointerExitAndEnter(rayCastEntity); } } } /** * @internal */ _destroy(): void { // @ts-ignore const htmlCanvas = this._canvas._webCanvas as HTMLCanvasElement; htmlCanvas.onpointerdown = htmlCanvas.onpointerup = htmlCanvas.onpointerout = htmlCanvas.onpointermove = null; this._nativeEvents.length = 0; this._pointerPool.length = 0; this._pointers.length = 0; this._currentPosition = null; this._currentEnteredEntity = null; this._currentPressedEntity = null; this._engine = null; this._canvas = null; } private _overallPointers(): void { const { _pointers: pointers } = this; let deleteCount = 0; const totalCount = pointers.length; for (let i = 0; i < totalCount; i++) { if (pointers[i].phase === PointerPhase.Leave) { deleteCount++; } else { if (deleteCount > 0) { pointers[i - deleteCount] = pointers[i]; } } } pointers.length = totalCount - deleteCount; this._needOverallPointers = false; } private _getIndexByPointerID(pointerId: number): number { const { _pointers: pointers } = this; for (let i = pointers.length - 1; i >= 0; i--) { if (pointers[i]._uniqueID === pointerId) { return i; } } return -1; } private _addPointer(pointerId: number, x: number, y: number, phase: PointerPhase): void { const { _pointers: pointers } = this; const lastCount = pointers.length; if (lastCount === 0 || this._multiPointerEnabled) { const { _pointerPool: pointerPool } = this; // Get Pointer smallest index. let i = 0; for (; i < lastCount; i++) { if (pointers[i].id > i) { break; } } let pointer = pointerPool[i]; if (!pointer) { pointer = pointerPool[i] = new Pointer(i); } pointer._uniqueID = pointerId; pointer._needUpdate = true; pointer.position.setValue(x, y); pointer.phase = phase; pointers.splice(i, 0, pointer); } } private _removePointer(pointerIndex: number): void { this._pointers[pointerIndex].phase = PointerPhase.Leave; } private _updatePointer(pointerIndex: number, x: number, y: number, phase: PointerPhase): void { const updatedPointer = this._pointers[pointerIndex]; updatedPointer.position.setValue(x, y); updatedPointer._needUpdate = true; updatedPointer.phase = phase; } private _handlePointerEvent(nativeEvents: PointerEvent[]): void { const { _pointers: pointers, _keyEventList: keyEventList } = this; let activePointerCount = pointers.length; const nativeEventsLen = nativeEvents.length; for (let i = 0; i < nativeEventsLen; i++) { const evt = nativeEvents[i]; let pointerIndex = this._getIndexByPointerID(evt.pointerId); switch (evt.type) { case "pointerdown": if (pointerIndex === -1) { this._addPointer(evt.pointerId, evt.offsetX, evt.offsetY, PointerPhase.Down); activePointerCount++; } else { this._updatePointer(pointerIndex, evt.offsetX, evt.offsetY, PointerPhase.Down); } activePointerCount === 1 && (keyEventList[this._keyEventCount++] = PointerKeyEvent.Down); break; case "pointerup": if (pointerIndex >= 0) { this._updatePointer(pointerIndex, evt.offsetX, evt.offsetY, PointerPhase.Up); activePointerCount === 1 && (keyEventList[this._keyEventCount++] = PointerKeyEvent.Up); } break; case "pointermove": if (pointerIndex === -1) { this._addPointer(evt.pointerId, evt.offsetX, evt.offsetY, PointerPhase.Move); activePointerCount++; } else { this._updatePointer(pointerIndex, evt.offsetX, evt.offsetY, PointerPhase.Move); } break; case "pointerout": if (pointerIndex >= 0) { this._removePointer(pointerIndex); --activePointerCount === 0 && (keyEventList[this._keyEventCount++] = PointerKeyEvent.Leave); this._needOverallPointers = true; } break; } } const pointerCount = pointers.length; if (pointerCount > 0) { const { _canvas: canvas, _currentPosition: currentPosition } = this; // @ts-ignore const pixelRatioWidth = canvas.width / (canvas._webCanvas as HTMLCanvasElement).clientWidth; // @ts-ignore const pixelRatioHeight = canvas.height / (canvas._webCanvas as HTMLCanvasElement).clientHeight; if (activePointerCount === 0) { // Get the pointer coordinates when leaving, and use it to correctly dispatch the click event. const lastNativeEvent = nativeEvents[nativeEventsLen - 1]; currentPosition.setValue(lastNativeEvent.offsetX * pixelRatioWidth, lastNativeEvent.offsetY * pixelRatioHeight); } else { currentPosition.setValue(0, 0); for (let i = 0; i < pointerCount; i++) { const pointer = pointers[i]; const { position } = pointer; if (pointer._needUpdate) { position.setValue(position.x * pixelRatioWidth, position.y * pixelRatioHeight); pointer._needUpdate = false; } currentPosition.add(position); } currentPosition.scale(1 / pointerCount); } } nativeEvents.length = 0; } private _pointerRayCast(): Entity { if (this._pointers.length > 0) { const { _tempPoint: point, _tempRay: ray, _tempHitResult: hitResult } = PointerManager; const { _activeCameras: cameras } = this._engine.sceneManager.activeScene; const x = this._currentPosition.x / this._canvas.width; const y = this._currentPosition.y / this._canvas.height; for (let i = cameras.length - 1; i >= 0; i--) { const camera = cameras[i]; if (!camera.enabled || camera.renderTarget) { continue; } const { x: vpX, y: vpY, z: vpW, w: vpH } = camera.viewport; if (x >= vpX && y >= vpY && x - vpX <= vpW && y - vpY <= vpH) { point.setValue((x - vpX) / vpW, (y - vpY) / vpH); // TODO: Only check which colliders have listened to the input. if (this._engine.physicsManager.raycast(camera.viewportPointToRay(point, ray), hitResult)) { return hitResult.entity; } else if (camera.clearFlags === CameraClearFlags.DepthColor) { return null; } } } } return null; } private _firePointerDrag(): void { if (this._currentPressedEntity) { const scripts = this._currentPressedEntity._scripts; for (let i = scripts.length - 1; i >= 0; i--) { scripts.get(i).onPointerDrag(); } } } private _firePointerExitAndEnter(rayCastEntity: Entity): void { if (this._currentEnteredEntity !== rayCastEntity) { if (this._currentEnteredEntity) { const scripts = this._currentEnteredEntity._scripts; for (let i = scripts.length - 1; i >= 0; i--) { scripts.get(i).onPointerExit(); } } if (rayCastEntity) { const scripts = rayCastEntity._scripts; for (let i = scripts.length - 1; i >= 0; i--) { scripts.get(i).onPointerEnter(); } } this._currentEnteredEntity = rayCastEntity; } } private _firePointerDown(rayCastEntity: Entity): void { if (rayCastEntity) { const scripts = rayCastEntity._scripts; for (let i = scripts.length - 1; i >= 0; i--) { scripts.get(i).onPointerDown(); } } this._currentPressedEntity = rayCastEntity; } private _firePointerUpAndClick(rayCastEntity: Entity): void { const { _currentPressedEntity: pressedEntity } = this; if (pressedEntity) { const sameTarget = pressedEntity === rayCastEntity; const scripts = pressedEntity._scripts; for (let i = scripts.length - 1; i >= 0; i--) { const script = scripts.get(i); sameTarget && script.onPointerClick(); script.onPointerUp(); } this._currentPressedEntity = null; } } } /** * @internal */ enum PointerKeyEvent { Down, Up, Leave }
the_stack
import { PropertyValues, ReactiveElement } from "lit"; import { customElement, property, state } from "lit/decorators"; import { applyThemesOnElement } from "../../../common/dom/apply_themes_on_element"; import "../../../components/entity/ha-state-label-badge"; import "../../../components/ha-svg-icon"; import type { LovelaceBadgeConfig, LovelaceCardConfig, LovelaceViewConfig, LovelaceViewElement, } from "../../../data/lovelace"; import type { HomeAssistant } from "../../../types"; import { createErrorBadgeConfig, createErrorBadgeElement, } from "../badges/hui-error-badge"; import type { HuiErrorCard } from "../cards/hui-error-card"; import { processConfigEntities } from "../common/process-config-entities"; import { createBadgeElement } from "../create-element/create-badge-element"; import { createCardElement } from "../create-element/create-card-element"; import { createErrorCardConfig, createErrorCardElement, } from "../create-element/create-element-base"; import { createViewElement } from "../create-element/create-view-element"; import { showCreateCardDialog } from "../editor/card-editor/show-create-card-dialog"; import { showEditCardDialog } from "../editor/card-editor/show-edit-card-dialog"; import { confDeleteCard } from "../editor/delete-card"; import { generateLovelaceViewStrategy } from "../strategies/get-strategy"; import type { Lovelace, LovelaceBadge, LovelaceCard } from "../types"; import { PANEL_VIEW_LAYOUT, DEFAULT_VIEW_LAYOUT } from "./const"; declare global { // for fire event interface HASSDomEvents { "ll-create-card": undefined; "ll-edit-card": { path: [number] | [number, number] }; "ll-delete-card": { path: [number] | [number, number] }; } } @customElement("hui-view") export class HUIView extends ReactiveElement { @property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public lovelace!: Lovelace; @property({ type: Boolean }) public narrow!: boolean; @property({ type: Number }) public index!: number; @state() private _cards: Array<LovelaceCard | HuiErrorCard> = []; @state() private _badges: LovelaceBadge[] = []; private _layoutElementType?: string; private _layoutElement?: LovelaceViewElement; private _viewConfigTheme?: string; // Public to make demo happy public createCardElement(cardConfig: LovelaceCardConfig) { const element = createCardElement(cardConfig) as LovelaceCard; try { element.hass = this.hass; } catch (e: any) { return createErrorCardElement( createErrorCardConfig(e.message, cardConfig) ); } element.addEventListener( "ll-rebuild", (ev: Event) => { // In edit mode let it go to hui-root and rebuild whole view. if (!this.lovelace!.editMode) { ev.stopPropagation(); this._rebuildCard(element, cardConfig); } }, { once: true } ); return element; } public createBadgeElement(badgeConfig: LovelaceBadgeConfig) { const element = createBadgeElement(badgeConfig) as LovelaceBadge; try { element.hass = this.hass; } catch (e: any) { return createErrorBadgeElement(createErrorBadgeConfig(e.message)); } element.addEventListener( "ll-badge-rebuild", () => { this._rebuildBadge(element, badgeConfig); }, { once: true } ); return element; } protected createRenderRoot() { return this; } public willUpdate(changedProperties: PropertyValues): void { super.willUpdate(changedProperties); /* We need to handle the following use cases: - initialization: create layout element, populate - config changed to view with same layout element - config changed to view with different layout element - forwarded properties hass/narrow/lovelace/cards/badges change - cards/badges change if one is rebuild when it was loaded later - lovelace changes if edit mode is enabled or config has changed */ const oldLovelace = changedProperties.get("lovelace") as this["lovelace"]; // If config has changed, create element if necessary and set all values. if ( changedProperties.has("index") || (changedProperties.has("lovelace") && (!oldLovelace || this.lovelace.config.views[this.index] !== oldLovelace.config.views[this.index])) ) { this._initializeConfig(); } } protected update(changedProperties) { super.update(changedProperties); // If no layout element, we're still creating one if (this._layoutElement) { // Config has not changed. Just props if (changedProperties.has("hass")) { this._badges.forEach((badge) => { try { badge.hass = this.hass; } catch (e: any) { this._rebuildBadge(badge, createErrorBadgeConfig(e.message)); } }); this._cards.forEach((element) => { try { element.hass = this.hass; } catch (e: any) { this._rebuildCard(element, createErrorCardConfig(e.message, null)); } }); this._layoutElement.hass = this.hass; const oldHass = changedProperties.get("hass") as | this["hass"] | undefined; if ( !oldHass || this.hass.themes !== oldHass.themes || this.hass.selectedTheme !== oldHass.selectedTheme ) { applyThemesOnElement(this, this.hass.themes, this._viewConfigTheme); } } if (changedProperties.has("narrow")) { this._layoutElement.narrow = this.narrow; } if (changedProperties.has("lovelace")) { this._layoutElement.lovelace = this.lovelace; } if (changedProperties.has("_cards")) { this._layoutElement.cards = this._cards; } if (changedProperties.has("_badges")) { this._layoutElement.badges = this._badges; } } } private async _initializeConfig() { let viewConfig = this.lovelace.config.views[this.index]; let isStrategy = false; if (viewConfig.strategy) { isStrategy = true; viewConfig = await generateLovelaceViewStrategy({ hass: this.hass, config: this.lovelace.config, narrow: this.narrow, view: viewConfig, }); } viewConfig = { ...viewConfig, type: viewConfig.panel ? PANEL_VIEW_LAYOUT : viewConfig.type || DEFAULT_VIEW_LAYOUT, }; // Create a new layout element if necessary. let addLayoutElement = false; if (!this._layoutElement || this._layoutElementType !== viewConfig.type) { addLayoutElement = true; this._createLayoutElement(viewConfig); } this._createBadges(viewConfig); this._createCards(viewConfig); this._layoutElement!.isStrategy = isStrategy; this._layoutElement!.hass = this.hass; this._layoutElement!.narrow = this.narrow; this._layoutElement!.lovelace = this.lovelace; this._layoutElement!.index = this.index; this._layoutElement!.cards = this._cards; this._layoutElement!.badges = this._badges; applyThemesOnElement(this, this.hass.themes, viewConfig.theme); this._viewConfigTheme = viewConfig.theme; if (addLayoutElement) { while (this.lastChild) { this.removeChild(this.lastChild); } this.appendChild(this._layoutElement!); } } private _createLayoutElement(config: LovelaceViewConfig): void { this._layoutElement = createViewElement(config) as LovelaceViewElement; this._layoutElementType = config.type; this._layoutElement.addEventListener("ll-create-card", () => { showCreateCardDialog(this, { lovelaceConfig: this.lovelace.config, saveConfig: this.lovelace.saveConfig, path: [this.index], }); }); this._layoutElement.addEventListener("ll-edit-card", (ev) => { showEditCardDialog(this, { lovelaceConfig: this.lovelace.config, saveConfig: this.lovelace.saveConfig, path: ev.detail.path, }); }); this._layoutElement.addEventListener("ll-delete-card", (ev) => { confDeleteCard(this, this.hass!, this.lovelace!, ev.detail.path); }); } private _createBadges(config: LovelaceViewConfig): void { if (!config || !config.badges || !Array.isArray(config.badges)) { this._badges = []; return; } const badges = processConfigEntities(config.badges as any); this._badges = badges.map((badge) => { const element = createBadgeElement(badge); try { element.hass = this.hass; } catch (e: any) { return createErrorBadgeElement(createErrorBadgeConfig(e.message)); } return element; }); } private _createCards(config: LovelaceViewConfig): void { if (!config || !config.cards || !Array.isArray(config.cards)) { this._cards = []; return; } this._cards = config.cards.map((cardConfig) => { const element = this.createCardElement(cardConfig); try { element.hass = this.hass; } catch (e: any) { return createErrorCardElement( createErrorCardConfig(e.message, cardConfig) ); } return element; }); } private _rebuildCard( cardElToReplace: LovelaceCard, config: LovelaceCardConfig ): void { let newCardEl = this.createCardElement(config); try { newCardEl.hass = this.hass; } catch (e: any) { newCardEl = createErrorCardElement( createErrorCardConfig(e.message, config) ); } if (cardElToReplace.parentElement) { cardElToReplace.parentElement!.replaceChild(newCardEl, cardElToReplace); } this._cards = this._cards!.map((curCardEl) => curCardEl === cardElToReplace ? newCardEl : curCardEl ); } private _rebuildBadge( badgeElToReplace: LovelaceBadge, config: LovelaceBadgeConfig ): void { let newBadgeEl = this.createBadgeElement(config); try { newBadgeEl.hass = this.hass; } catch (e: any) { newBadgeEl = createErrorBadgeElement(createErrorBadgeConfig(e.message)); } if (badgeElToReplace.parentElement) { badgeElToReplace.parentElement!.replaceChild( newBadgeEl, badgeElToReplace ); } this._badges = this._badges!.map((curBadgeEl) => curBadgeEl === badgeElToReplace ? newBadgeEl : curBadgeEl ); } } declare global { interface HTMLElementTagNameMap { "hui-view": HUIView; } }
the_stack
import test, { Macro } from 'ava'; import { fc, testProp } from 'ava-fast-check'; import * as bitcoreLibCash from 'bitcore-lib-cash'; import { crackHdPrivateNodeFromHdPublicNodeAndChildPrivateNode, decodeHdKey, decodeHdPrivateKey, decodeHdPublicKey, deriveHdPath, deriveHdPrivateNodeChild, deriveHdPrivateNodeFromSeed, deriveHdPrivateNodeIdentifier, deriveHdPublicNode, deriveHdPublicNodeChild, deriveHdPublicNodeIdentifier, encodeHdPrivateKey, encodeHdPublicKey, HdKeyDecodingError, HdKeyParameters, HdKeyVersion, HdNodeCrackingError, HdNodeDerivationError, HdPrivateNode, HdPrivateNodeInvalid, HdPrivateNodeKnownParent, HdPrivateNodeValid, HdPublicNode, hexToBin, instantiateBIP32Crypto, validateSecp256k1PrivateKey, } from '../lib'; const seed = Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); const xprv = 'xprv9s21ZrQH143K2JbpEjGU94NcdKSASB7LuXvJCTsxuENcGN1nVG7QjMnBZ6zZNcJaiJogsRaLaYFFjs48qt4Fg7y1GnmrchQt1zFNu6QVnta'; const tprv = 'tprv8ZgxMBicQKsPd7qLuJ7yJhzbwSrNfh9MF5qR4tJRPCs63xksUdTAF79dUHADNygu5kLTsXC6jtq4Cibsy6QCVBEboRzAH48vw5zoLkJTuso'; const xpub = 'xpub661MyMwAqRbcEngHLkoUWCKMBMGeqdqCGkqtzrHaTZub9ALw2oRfHA6fQP5n5X9VHStaNTBYomkSb8BFhUGavwD3RG1qvMkEKceTavTp2Tm'; const tpub = 'tpubD6NzVbkrYhZ4Was8nwnZi7eiWUNJq2LFpPSCMQLioUfUtT1e72GkRbmVeRAZc26j5MRUz2hRLsaVHJfs6L7ppNfLUrm9btQTuaEsLrT7D87'; const maxUint8Number = 255; const fcUint8Array = (minLength: number, maxLength: number) => fc .array(fc.integer(0, maxUint8Number), minLength, maxLength) .map((a) => Uint8Array.from(a)); const maximumDepth = 255; const maximumChildIndex = 0xffffffff; const fingerprintLength = 4; const chainCodeLength = 32; const privateKeyLength = 32; const publicKeyLength = 33; const hardenedIndexOffset = 0x80000000; const maximumNonHardenedIndex = hardenedIndexOffset - 1; test('[crypto] deriveHdPrivateNodeFromSeed', async (t) => { const crypto = await instantiateBIP32Crypto(); const valid = { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), privateKey: hexToBin( '330fd355e141910d33bbe84c369b87a209dd18b81095912be766b2b5a9d72bc4' ), valid: true, } as HdPrivateNodeValid; const invalid = { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, invalidPrivateKey: hexToBin( '330fd355e141910d33bbe84c369b87a209dd18b81095912be766b2b5a9d72bc4' ), parentFingerprint: hexToBin('00000000'), valid: false, } as HdPrivateNodeInvalid; const either = deriveHdPrivateNodeFromSeed(crypto, seed); const validNode = deriveHdPrivateNodeFromSeed(crypto, seed, true); const invalidNode = deriveHdPrivateNodeFromSeed(crypto, seed, false); t.deepEqual(either, valid as HdPrivateNode); t.deepEqual(validNode, valid); t.deepEqual(invalidNode, invalid); }); test('[crypto] deriveHdPrivateNodeIdentifier', async (t) => { const crypto = await instantiateBIP32Crypto(); const { node } = decodeHdPrivateKey(crypto, xprv) as HdKeyParameters< HdPrivateNodeValid >; t.deepEqual( deriveHdPrivateNodeIdentifier(crypto, node), hexToBin('15c918d389673c6cd0660050f268a843361e1111') ); }); test('[crypto] deriveHdPublicNodeIdentifier', async (t) => { const crypto = await instantiateBIP32Crypto(); const { node } = decodeHdPublicKey(crypto, xpub) as HdKeyParameters< HdPublicNode >; t.deepEqual( deriveHdPublicNodeIdentifier(crypto, node), hexToBin('15c918d389673c6cd0660050f268a843361e1111') ); }); test('[crypto] decodeHdKey', async (t) => { const crypto = await instantiateBIP32Crypto(); t.deepEqual(decodeHdKey(crypto, xprv), { node: { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), privateKey: hexToBin( '330fd355e141910d33bbe84c369b87a209dd18b81095912be766b2b5a9d72bc4' ), valid: true, }, version: HdKeyVersion.mainnetPrivateKey, }); t.deepEqual(decodeHdKey(crypto, xpub), { node: { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), publicKey: hexToBin( '02be99138b48b430a8ee40bf8b56c8ebc584c363774010a9bfe549a87126e61746' ), }, version: HdKeyVersion.mainnetPublicKey, }); }); test('[crypto] decodeHdKey: errors', async (t) => { const crypto = await instantiateBIP32Crypto(); t.deepEqual( decodeHdKey(crypto, '#badKey'), HdKeyDecodingError.unknownCharacter ); t.deepEqual( decodeHdKey(crypto, 'xprv1234'), HdKeyDecodingError.incorrectLength ); t.deepEqual( decodeHdKey( crypto, 'xpub661MyMwAqRbcEngHLkoUWCKMBMGeqdqCGkqtzrHaTZub9ALw2oRfHA6fQP5n5X9VHStaNTBYomkSb8BFhUGavwD3RG1qvMkEKceTavTp2Ta' ), HdKeyDecodingError.invalidChecksum ); }); test('[crypto] decodeHdPrivateKey', async (t) => { const crypto = await instantiateBIP32Crypto(); t.deepEqual(decodeHdPrivateKey(crypto, xprv), { network: 'mainnet', node: { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), privateKey: hexToBin( '330fd355e141910d33bbe84c369b87a209dd18b81095912be766b2b5a9d72bc4' ), valid: true, }, }); t.deepEqual(decodeHdPrivateKey(crypto, tprv), { network: 'testnet', node: { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), privateKey: hexToBin( '330fd355e141910d33bbe84c369b87a209dd18b81095912be766b2b5a9d72bc4' ), valid: true, }, }); }); test('[crypto] decodeHdPrivateKey: errors', async (t) => { const crypto = await instantiateBIP32Crypto(); t.deepEqual( decodeHdPrivateKey(crypto, xpub), HdKeyDecodingError.privateKeyExpected ); t.deepEqual( decodeHdPrivateKey( crypto, '1111111111111FF9QeH94hg7KAjgjUqkHUqbrw5wWQLoRNfRhB4cHUDCJxx2HfNb5qDiAjpbKjXeLJSknuzDmja42174H9Es1XbY24sZts9' ), HdKeyDecodingError.unknownVersion ); const xprvWith0FilledKey = 'xprv9s21ZrQH143K2JbpEjGU94NcdKSASB7LuXvJCTsxuENcGN1nVG7QjMnBZ6c54tCKNErugtr5mi7oyGaDVrYe4SE5u1GnzYHmjDKuKg4vuNm'; t.deepEqual( decodeHdPrivateKey(crypto, xprvWith0FilledKey), HdKeyDecodingError.invalidPrivateNode ); const xprvWith255FilledKey = 'xprv9s21ZrQH143K2JbpEjGU94NcdKSASB7LuXvJCTsxuENcGN1nVG7QjMnBZ8YpF7eMDfY8piRngHjovbAzQyAMi94xgeLuEgyfisLHpC7G5ST'; t.deepEqual( decodeHdPrivateKey(crypto, xprvWith255FilledKey), HdKeyDecodingError.invalidPrivateNode ); t.deepEqual( decodeHdPrivateKey( crypto, 'xprv9s21ZrQH143K2JbpEjGU94NcdKSASB7LuXvJCTsxuENcGN1nVG7QjMnBhegPMjkj1oGSFcmBkMX3xdwcMy6NSgrHvmqJptpUW5xGjg7kifZ' ), HdKeyDecodingError.missingPrivateKeyPaddingByte ); }); test('[crypto] decodeHdPublicKey', async (t) => { const crypto = await instantiateBIP32Crypto(); t.deepEqual(decodeHdPublicKey(crypto, xpub), { network: 'mainnet', node: { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), publicKey: hexToBin( '02be99138b48b430a8ee40bf8b56c8ebc584c363774010a9bfe549a87126e61746' ), }, }); t.deepEqual(decodeHdPublicKey(crypto, tpub), { network: 'testnet', node: { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), publicKey: hexToBin( '02be99138b48b430a8ee40bf8b56c8ebc584c363774010a9bfe549a87126e61746' ), }, }); }); test('[crypto] decodeHdPublicKey: errors', async (t) => { const crypto = await instantiateBIP32Crypto(); t.deepEqual( decodeHdPublicKey(crypto, xprv), HdKeyDecodingError.publicKeyExpected ); t.deepEqual( decodeHdPublicKey( crypto, '1111111111111FF9QeH94hg7KAjgjUqkHUqbrw5wWQLoRNfRhB4cHUDCJxx2HfNb5qDiAjpbKjXeLJSknuzDmja42174H9Es1XbY24sZts9' ), HdKeyDecodingError.unknownVersion ); }); test('[crypto] encodeHdPrivateKey', async (t) => { const crypto = await instantiateBIP32Crypto(); t.deepEqual( encodeHdPrivateKey(crypto, { network: 'mainnet', node: { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), privateKey: hexToBin( '330fd355e141910d33bbe84c369b87a209dd18b81095912be766b2b5a9d72bc4' ), valid: true, }, }), xprv ); t.deepEqual( encodeHdPrivateKey(crypto, { network: 'testnet', node: { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), privateKey: hexToBin( '330fd355e141910d33bbe84c369b87a209dd18b81095912be766b2b5a9d72bc4' ), valid: true, }, }), tprv ); }); test('[crypto] encodeHdPublicKey', async (t) => { const crypto = await instantiateBIP32Crypto(); t.deepEqual( encodeHdPublicKey(crypto, { network: 'mainnet', node: { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), publicKey: hexToBin( '02be99138b48b430a8ee40bf8b56c8ebc584c363774010a9bfe549a87126e61746' ), }, }), xpub ); t.deepEqual( encodeHdPublicKey(crypto, { network: 'testnet', node: { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), publicKey: hexToBin( '02be99138b48b430a8ee40bf8b56c8ebc584c363774010a9bfe549a87126e61746' ), }, }), tpub ); }); test('[crypto] deriveHdPublicNode', async (t) => { const crypto = await instantiateBIP32Crypto(); const privateParams = decodeHdPrivateKey(crypto, xprv); if (typeof privateParams === 'string') { t.fail(privateParams); return; } t.deepEqual(deriveHdPublicNode(crypto, privateParams.node), { chainCode: hexToBin( '18aab7e9ef169f3029d93651d0c85303cbcc2ac559ccd04c324a2e678ef26dc9' ), childIndex: 0, depth: 0, parentFingerprint: hexToBin('00000000'), publicKey: hexToBin( '02be99138b48b430a8ee40bf8b56c8ebc584c363774010a9bfe549a87126e61746' ), }); }); test('[crypto] deriveHdPrivateNodeChild', async (t) => { const crypto = await instantiateBIP32Crypto(); const master = decodeHdPrivateKey(crypto, xprv); const hardenedIndex0Child = decodeHdPrivateKey( crypto, 'xprv9u4S6TaiPQaF7FS24QFpRP6hjff4jXNwwYTkVNC6f6YzHj2a6G28aRN1D6Az82SxMeBivpVS3gDDXyQiu3RANTqWy34Zxi9JN76zSwkjqPF' ); const index1GrandChild = decodeHdPrivateKey( crypto, 'xprv9w8PdihBAeR4xgGYWWqBnmDTrpWEW1QjuYAUkR7A6X48q1iQVgN433aSFxQGgtureVz7cCyi5zfuMTtBF3AkanjtvNs9m8u2JobxNfphSi3' ); if ( typeof master === 'string' || typeof hardenedIndex0Child === 'string' || typeof index1GrandChild === 'string' ) { t.fail(); return; } const hardenedIndex0 = 0x80000000; const result0 = deriveHdPrivateNodeChild( crypto, master.node, hardenedIndex0 ) as HdPrivateNodeValid; const result1 = deriveHdPrivateNodeChild(crypto, result0, 1); t.deepEqual(result0, { ...hardenedIndex0Child.node, parentIdentifier: hexToBin('15c918d389673c6cd0660050f268a843361e1111'), }); t.deepEqual(result1, { ...index1GrandChild.node, parentIdentifier: hexToBin('2f2bc501c943dd7f17904b612c090dd88270cc59'), }); }); test('[crypto] deriveHdPrivateNodeChild: errors', async (t) => { const crypto = await instantiateBIP32Crypto(); const { node } = decodeHdPrivateKey(crypto, xprv) as HdKeyParameters< HdPrivateNodeValid >; const max = 0xffffffff; t.deepEqual( deriveHdPrivateNodeChild(crypto, node, max + 1), HdNodeDerivationError.childIndexExceedsMaximum ); }); test('[crypto] deriveHdPublicNodeChild', async (t) => { const crypto = await instantiateBIP32Crypto(); const { node } = decodeHdPrivateKey(crypto, xprv) as HdKeyParameters< HdPrivateNodeValid >; const parentPublic = deriveHdPublicNode(crypto, node); const derivationIndex = 0; const child = deriveHdPrivateNodeChild( crypto, node, derivationIndex ) as HdPrivateNodeKnownParent; const expectedPublic = deriveHdPublicNode(crypto, child); t.deepEqual( deriveHdPublicNodeChild(crypto, parentPublic, derivationIndex), expectedPublic ); }); test('[crypto] deriveHdPublicNodeChild: errors', async (t) => { const crypto = await instantiateBIP32Crypto(); const { node } = decodeHdPublicKey(crypto, xpub) as HdKeyParameters< HdPublicNode >; const hardened0 = 0x80000000; t.deepEqual( deriveHdPublicNodeChild(crypto, node, hardened0), HdNodeDerivationError.hardenedDerivationRequiresPrivateNode ); }); test('[crypto] deriveHdPath', async (t) => { const crypto = await instantiateBIP32Crypto(); const { node: privateNode } = decodeHdPrivateKey( crypto, xprv ) as HdKeyParameters<HdPrivateNodeValid>; const publicNode = deriveHdPublicNode(crypto, privateNode); t.deepEqual( deriveHdPath(crypto, privateNode, 'm') as HdPrivateNodeValid, privateNode ); t.deepEqual( deriveHdPath(crypto, publicNode, 'M') as HdPublicNode, publicNode ); t.deepEqual(deriveHdPath(crypto, privateNode, "m/0'/1"), { ...(decodeHdPrivateKey( crypto, 'xprv9w8PdihBAeR4xgGYWWqBnmDTrpWEW1QjuYAUkR7A6X48q1iQVgN433aSFxQGgtureVz7cCyi5zfuMTtBF3AkanjtvNs9m8u2JobxNfphSi3' ) as HdKeyParameters<HdPrivateNodeValid>).node, parentIdentifier: hexToBin('2f2bc501c943dd7f17904b612c090dd88270cc59'), }); t.deepEqual( deriveHdPath(crypto, publicNode, 'M/0/1/2/3'), deriveHdPublicNode( crypto, deriveHdPath(crypto, privateNode, 'm/0/1/2/3') as HdPrivateNodeKnownParent ) ); t.deepEqual( deriveHdPath(crypto, privateNode, "m/0'/1'/2'/3'"), deriveHdPath( crypto, privateNode, 'm/2147483648/2147483649/2147483650/2147483651' ) ); }); test('[crypto] deriveHdPath: errors', async (t) => { const crypto = await instantiateBIP32Crypto(); const { node: privateNode } = decodeHdPrivateKey( crypto, xprv ) as HdKeyParameters<HdPrivateNodeValid>; const publicNode = deriveHdPublicNode(crypto, privateNode); t.deepEqual( deriveHdPath(crypto, privateNode, 'm/bad/1'), HdNodeDerivationError.invalidDerivationPath ); t.deepEqual( deriveHdPath(crypto, privateNode, 'M'), HdNodeDerivationError.invalidPrivateDerivationPrefix ); t.deepEqual( deriveHdPath(crypto, publicNode, 'm'), HdNodeDerivationError.invalidPublicDerivationPrefix ); t.deepEqual( deriveHdPath(crypto, privateNode, 'm/0/4294967296/0'), HdNodeDerivationError.childIndexExceedsMaximum ); t.deepEqual( deriveHdPath(crypto, publicNode, "M/0/0'/0"), HdNodeDerivationError.hardenedDerivationRequiresPrivateNode ); t.deepEqual( deriveHdPath(crypto, publicNode, 'M/0/2147483648/0'), HdNodeDerivationError.hardenedDerivationRequiresPrivateNode ); }); test('[crypto] crackHdPrivateNodeFromHdPublicNodeAndChildPrivateNode', async (t) => { const crypto = await instantiateBIP32Crypto(); const { node: parentPrivateNode } = decodeHdPrivateKey( crypto, xprv ) as HdKeyParameters<HdPrivateNodeValid>; const parentPublicNode = deriveHdPublicNode(crypto, parentPrivateNode); const nonHardenedChildNode = deriveHdPath( crypto, parentPrivateNode, 'm/1234' ) as HdPrivateNodeKnownParent; const hardenedChildNode = deriveHdPath( crypto, parentPrivateNode, "m/1234'" ) as HdPrivateNodeKnownParent; const hardenedChildPublicNode = deriveHdPublicNode(crypto, hardenedChildNode); const nonHardenedGrandchildNode = deriveHdPath( crypto, hardenedChildNode, 'm/1234' ) as HdPrivateNodeKnownParent; t.deepEqual( crackHdPrivateNodeFromHdPublicNodeAndChildPrivateNode( crypto, parentPublicNode, nonHardenedChildNode ), parentPrivateNode ); t.deepEqual( crackHdPrivateNodeFromHdPublicNodeAndChildPrivateNode( crypto, hardenedChildPublicNode, nonHardenedGrandchildNode ), hardenedChildNode ); t.deepEqual( crackHdPrivateNodeFromHdPublicNodeAndChildPrivateNode( crypto, parentPublicNode, hardenedChildNode ), HdNodeCrackingError.cannotCrackHardenedDerivation ); }); // eslint-disable-next-line complexity const bip32Vector: Macro<[string, string, string, string]> = async ( t, seedHex, path, hdPrivateKey, hdPublicKey // eslint-disable-next-line max-params ) => { const crypto = await instantiateBIP32Crypto(); const master = deriveHdPrivateNodeFromSeed(crypto, hexToBin(seedHex)); if (!master.valid) { t.log(seedHex, master.invalidPrivateKey); t.fail('Astronomically rare hash found!'); return; } const childNode = deriveHdPath(crypto, master, path); if (typeof childNode === 'string') { t.fail(childNode); return; } const vectorXprv = encodeHdPrivateKey(crypto, { network: 'mainnet', node: childNode, }); t.deepEqual(vectorXprv, hdPrivateKey); const decodedPrivate = decodeHdPrivateKey(crypto, hdPrivateKey); if (typeof decodedPrivate === 'string') { t.fail(decodedPrivate); return; } t.deepEqual( childNode.parentIdentifier?.slice(0, fingerprintLength), path === 'm' ? undefined : decodedPrivate.node.parentFingerprint ); t.deepEqual(childNode, { ...decodedPrivate.node, ...(path === 'm' ? {} : { parentIdentifier: childNode.parentIdentifier }), }); const decodedPublic = decodeHdPublicKey(crypto, hdPublicKey); if (typeof decodedPublic === 'string') { t.fail(decodedPublic); return; } const publicNode = deriveHdPublicNode(crypto, childNode); t.deepEqual( publicNode.parentIdentifier?.slice(0, fingerprintLength), path === 'm' ? undefined : decodedPublic.node.parentFingerprint ); t.deepEqual(publicNode, { ...decodedPublic.node, ...(path === 'm' ? {} : { parentIdentifier: publicNode.parentIdentifier }), }); const vectorXpub = encodeHdPublicKey(crypto, { network: 'mainnet', node: publicNode, }); t.deepEqual(vectorXpub, hdPublicKey); }; // eslint-disable-next-line functional/immutable-data bip32Vector.title = (title, _, path) => `[crypto] BIP32 Vector – ${title ?? ''}: ${path}`; test( '#1.1', bip32Vector, '000102030405060708090a0b0c0d0e0f', 'm', 'xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi', 'xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8' ); test( '#1.2', bip32Vector, '000102030405060708090a0b0c0d0e0f', "m/0'", 'xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7', 'xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw' ); test( '#1.3', bip32Vector, '000102030405060708090a0b0c0d0e0f', "m/0'/1", 'xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs', 'xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ' ); test( '#1.4', bip32Vector, '000102030405060708090a0b0c0d0e0f', "m/0'/1/2'", 'xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM', 'xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5' ); test( '#1.5', bip32Vector, '000102030405060708090a0b0c0d0e0f', "m/0'/1/2'/2", 'xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334', 'xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV' ); test( '#1.6', bip32Vector, '000102030405060708090a0b0c0d0e0f', "m/0'/1/2'/2/1000000000", 'xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76', 'xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy' ); test( '#2.1', bip32Vector, 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542', 'm', 'xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U', 'xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB' ); test( '#2.2', bip32Vector, 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542', 'm/0', 'xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt', 'xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH' ); test( '#2.3', bip32Vector, 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542', "m/0/2147483647'", 'xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9', 'xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a' ); test( '#2.4', bip32Vector, 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542', "m/0/2147483647'/1", 'xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef', 'xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon' ); test( '#2.5', bip32Vector, 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542', "m/0/2147483647'/1/2147483646'", 'xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc', 'xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL' ); test( '#2.6', bip32Vector, 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542', "m/0/2147483647'/1/2147483646'/2", 'xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j', 'xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt' ); test( '#3.1', bip32Vector, '4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be', 'm', 'xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6', 'xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13' ); test( '#3.2', bip32Vector, '4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be', "m/0'", 'xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L', 'xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y' ); const fcBip32Path = () => fc .array(fc.integer(0, maximumChildIndex), 1, maximumDepth) .map( (array) => `m/${array .map((i) => i > hardenedIndexOffset ? `${i - hardenedIndexOffset}'` : `${i}` ) .join('/')}` ); testProp( '[fast-check] [crypto] HD key derivation is equivalent to bitcore-lib-cash', [fcBip32Path()], async (t, path: string) => { const crypto = await instantiateBIP32Crypto(); const privateNode = (decodeHdPrivateKey(crypto, xprv) as HdKeyParameters< HdPrivateNodeValid >).node; const node = deriveHdPath(crypto, privateNode, path) as HdPrivateNodeValid; const publicNode = deriveHdPublicNode(crypto, node); const resultPrv = encodeHdPrivateKey(crypto, { network: 'mainnet', node }); const resultPub = encodeHdPublicKey(crypto, { network: 'mainnet', node: publicNode, }); // eslint-disable-next-line new-cap, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access const bitcoreResult = bitcoreLibCash.HDPrivateKey(xprv).deriveChild(path); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access const bitcorePrv = bitcoreResult.xprivkey; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access const bitcorePub = bitcoreResult.xpubkey; t.deepEqual(resultPrv, bitcorePrv); t.deepEqual(resultPub, bitcorePub); }, { numRuns: 10 } ); testProp( '[fast-check] [crypto] encodeHdPublicKey <-> decodeHdPublicKey', [ fc.boolean(), fc.integer(0, maximumDepth), fc.integer(0, maximumChildIndex), fcUint8Array(fingerprintLength, fingerprintLength), fcUint8Array(chainCodeLength, chainCodeLength), fcUint8Array(publicKeyLength, publicKeyLength), ], async ( t, mainnet: boolean, depth: number, childIndex: number, parentFingerprint: Uint8Array, chainCode: Uint8Array, publicKey: Uint8Array // eslint-disable-next-line max-params ) => { const crypto = await instantiateBIP32Crypto(); const encoded = encodeHdPublicKey(crypto, { network: mainnet ? 'mainnet' : 'testnet', node: { chainCode, childIndex, depth, parentFingerprint, publicKey, }, }); t.deepEqual( encoded, encodeHdPublicKey( crypto, decodeHdPublicKey(crypto, encoded) as HdKeyParameters<HdPublicNode> ) ); } ); testProp( '[fast-check] [crypto] encodeHdPrivateKey <-> decodeHdPrivateKey', [ fc.boolean(), fc.integer(0, maximumDepth), fc.integer(0, maximumChildIndex), fcUint8Array(fingerprintLength, fingerprintLength), fcUint8Array(chainCodeLength, chainCodeLength), fcUint8Array(privateKeyLength, privateKeyLength), ], async ( t, mainnet: boolean, depth: number, childIndex: number, parentFingerprint: Uint8Array, chainCode: Uint8Array, privateKey: Uint8Array // eslint-disable-next-line max-params ) => { if (!validateSecp256k1PrivateKey(privateKey)) { t.pass(); return; } const crypto = await instantiateBIP32Crypto(); const encoded = encodeHdPrivateKey(crypto, { network: mainnet ? 'mainnet' : 'testnet', node: { chainCode, childIndex, depth, parentFingerprint, privateKey, valid: true, }, }); t.deepEqual( encoded, encodeHdPrivateKey( crypto, decodeHdPrivateKey(crypto, encoded) as HdKeyParameters< HdPrivateNodeValid > ) ); } ); testProp( '[fast-check] [crypto] derive non-hardened HD node <-> crack HD node', [ fc.integer(0, maximumDepth), fc.integer(0, maximumNonHardenedIndex), fcUint8Array(fingerprintLength, fingerprintLength), fcUint8Array(chainCodeLength, chainCodeLength), fcUint8Array(privateKeyLength, privateKeyLength), ], async ( t, depth: number, childIndexes: number, parentFingerprint: Uint8Array, chainCode: Uint8Array, privateKey: Uint8Array // eslint-disable-next-line max-params ) => { const crypto = await instantiateBIP32Crypto(); if (!validateSecp256k1PrivateKey(privateKey)) { t.pass(); return; } const parentXprv = encodeHdPrivateKey(crypto, { network: 'mainnet', node: { chainCode, childIndex: childIndexes, depth, parentFingerprint, privateKey, valid: true, }, }); const { node: parentPrivateNode } = decodeHdPrivateKey( crypto, parentXprv ) as HdKeyParameters<HdPrivateNodeValid>; const parentPublicNode = deriveHdPublicNode(crypto, parentPrivateNode); const nonHardenedChildNode = deriveHdPrivateNodeChild( crypto, parentPrivateNode, childIndexes ) as HdPrivateNodeValid; const crackedParentNode = crackHdPrivateNodeFromHdPublicNodeAndChildPrivateNode( crypto, parentPublicNode, nonHardenedChildNode ) as HdPrivateNodeValid; const crackedXprv = encodeHdPrivateKey(crypto, { network: 'mainnet', node: crackedParentNode, }); t.deepEqual(parentXprv, crackedXprv); } );
the_stack
import { Sdk, ISdk as t } from 'nger-core'; export declare class NativeSDk extends Sdk { getAccountInfoSync(): t.AccountInfo; getBatteryInfoSync(): t.GetBatteryInfoSyncResult; getExtConfigSync(): t.ExtInfo; getLaunchOptionsSync(): t.LaunchOptionsApp; getMenuButtonBoundingClientRect(): t.Rect; getStorageInfoSync(): t.GetStorageInfoSyncOption; getSystemInfoSync(): t.GetSystemInfoSyncResult; createAnimation(option: t.CreateAnimationOption): t.Animation; createAudioContext( /** `<audio/>` 组件的 id */ id: string, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<audio/>` 组件 */ component?: any): t.AudioContext; getBackgroundAudioManager(): t.BackgroundAudioManager; createCameraContext(): t.CameraContext; createCanvasContext( /** 要获取上下文的 `<canvas>` 组件 canvas-id 属性 */ canvasId: string, /** 在自定义组件下,当前组件实例的this,表示在这个自定义组件下查找拥有 canvas-id 的 `<canvas/>` ,如果省略则不在任何自定义组件内查找 */ component?: any): t.CanvasContext; downloadFile(option: t.DownloadFileOption): t.DownloadTask; getFileSystemManager(): t.FileSystemManager; createInnerAudioContext(): t.InnerAudioContext; createIntersectionObserver( /** 自定义组件实例 */ component: any, /** 选项 */ options: t.CreateIntersectionObserverOption): t.IntersectionObserver; createIntersectionObserver( /** 选项 */ options: t.CreateIntersectionObserverOption): IntersectionObserver; createLivePlayerContext( /** `<live-player/>` 组件的 id */ id: string, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<live-player/>` 组件 */ component?: any): t.LivePlayerContext; createLivePusherContext(): t.LivePusherContext; getLogManager(option: t.GetLogManagerOption): t.LogManager; createMapContext( /** `<map/>` 组件的 id */ mapId: string, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<map/>` 组件 */ component?: any): t.MapContext; getRecorderManager(): t.RecorderManager; request(option: t.RequestOption): t.RequestTask; createSelectorQuery(): t.SelectorQuery; connectSocket(option: t.ConnectSocketOption): t.SocketTask; getUpdateManager(): t.UpdateManager; uploadFile(option: t.UploadFileOption): t.UploadTask; createVideoContext( /** `<video/>` 组件的 id */ id: string, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<video/>` 组件 */ component: any): t.VideoContext; createWorker( /** worker 入口文件的**绝对路径** */ scriptPath: string): Worker; getStorageSync( /** 本地缓存中指定的 key */ key: string): any; canIUse( /** 使用 `${API}.${method}.${param}.${options}` 或者 `${component}.${attribute}.${option}` 方式来调用 */ schema: string): boolean; addCard(option: t.AddCardOption): void; addPhoneContact(option: t.AddPhoneContactOption): void; authorize(option: t.AuthorizeOption): void; canvasGetImageData(option: t.CanvasGetImageDataOption, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<canvas/>` 组件 */ component?: any): void; canvasPutImageData(option: t.CanvasPutImageDataOption, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<canvas/>` 组件 */ component?: any): void; canvasToTempFilePath(option: t.CanvasToTempFilePathOption, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<canvas/>` 组件 */ component?: any): void; checkIsSoterEnrolledInDevice(option: t.CheckIsSoterEnrolledInDeviceOption): void; checkIsSupportSoterAuthentication(option?: t.CheckIsSupportSoterAuthenticationOption): void; clearStorage(option?: t.ClearStorageOption): void; checkSession(option?: t.CheckSessionOption): void; chooseAddress(option?: t.ChooseAddressOption): void; chooseImage(option: t.ChooseImageOption): void; chooseInvoice(option?: t.ChooseInvoiceOption): void; chooseInvoiceTitle(option?: t.ChooseInvoiceTitleOption): void; chooseLocation(option?: t.ChooseLocationOption): void; chooseMessageFile(option: t.ChooseMessageFileOption): void; chooseVideo(option: t.ChooseVideoOption): void; clearStorageSync(): void; closeBLEConnection(option: t.CloseBLEConnectionOption): void; closeBluetoothAdapter(option?: t.CloseBluetoothAdapterOption): void; closeSocket(option: t.CloseSocketOption): void; compressImage(option: t.CompressImageOption): void; connectWifi(option: t.ConnectWifiOption): void; createBLEConnection(option: t.CreateBLEConnectionOption): void; getAvailableAudioSources(option?: t.GetAvailableAudioSourcesOption): void; getBLEDeviceCharacteristics(option: t.GetBLEDeviceCharacteristicsOption): void; getBLEDeviceServices(option: t.GetBLEDeviceServicesOption): void; getBackgroundAudioPlayerState(option?: t.GetBackgroundAudioPlayerStateOption): void; getBatteryInfo(option?: t.GetBatteryInfoOption): void; getBeacons(option?: t.GetBeaconsOption): void; getBluetoothAdapterState(option?: t.GetBluetoothAdapterStateOption): void; getBluetoothDevices(option?: t.GetBluetoothDevicesOption): void; getClipboardData(option?: t.GetClipboardDataOption): void; getConnectedBluetoothDevices(option: t.GetConnectedBluetoothDevicesOption): void; getConnectedWifi(option?: t.GetConnectedWifiOption): void; getExtConfig(option?: t.GetExtConfigOption): void; getFileInfo(option: t.WxGetFileInfoOption): void; getHCEState(option?: t.GetHCEStateOption): void; getImageInfo(option: t.GetImageInfoOption): void; getLocation(option: t.GetLocationOption): void; getNetworkType(option?: t.GetNetworkTypeOption): void; getSavedFileInfo(option: t.GetSavedFileInfoOption): void; getSavedFileList(option?: t.WxGetSavedFileListOption): void; getScreenBrightness(option?: t.GetScreenBrightnessOption): void; getSetting(option?: t.GetSettingOption): void; getShareInfo(option: t.GetShareInfoOption): void; getStorage(option: t.GetStorageOption): void; getStorageInfo(option?: t.GetStorageInfoOption): void; getSystemInfo(option?: t.GetSystemInfoOption): void; getUserInfo(option: t.GetUserInfoOption): void; getWeRunData(option?: t.GetWeRunDataOption): void; getWifiList(option?: t.GetWifiListOption): void; hideLoading(option?: t.HideLoadingOption): void; hideNavigationBarLoading(option?: t.HideNavigationBarLoadingOption): void; hideShareMenu(option?: t.HideShareMenuOption): void; hideTabBar(option: t.HideTabBarOption): void; hideTabBarRedDot(option: t.HideTabBarRedDotOption): void; hideToast(option?: t.HideToastOption): void; loadFontFace(option: t.LoadFontFaceOption): void; login(option: t.LoginOption): void; makePhoneCall(option: t.MakePhoneCallOption): void; navigateBack(option: t.NavigateBackOption): void; navigateBackMiniProgram(option: t.NavigateBackMiniProgramOption): void; navigateTo(option: t.NavigateToOption): void; navigateToMiniProgram(option: t.NavigateToMiniProgramOption): void; nextTick(callback: Function): void; notifyBLECharacteristicValueChange(option: t.NotifyBLECharacteristicValueChangeOption): void; offAppHide( /** 小程序切后台事件的回调函数 */ callback: t.OffAppHideCallback): void; offAppShow( /** 小程序切前台事件的回调函数 */ callback: t.OffAppShowCallback): void; offAudioInterruptionBegin( /** 音频因为受到系统占用而被中断开始事件的回调函数 */ callback: t.OffAudioInterruptionBeginCallback): void; offAudioInterruptionEnd( /** 音频中断结束事件的回调函数 */ callback: t.OffAudioInterruptionEndCallback): void; offError( /** 小程序错误事件的回调函数 */ callback: Function): void; offLocalServiceDiscoveryStop( /** mDNS 服务停止搜索的事件的回调函数 */ callback: t.OffLocalServiceDiscoveryStopCallback): void; offLocalServiceFound( /** mDNS 服务发现的事件的回调函数 */ callback: t.OffLocalServiceFoundCallback): void; offLocalServiceLost( /** mDNS 服务离开的事件的回调函数 */ callback: t.OffLocalServiceLostCallback): void; offLocalServiceResolveFail( /** mDNS 服务解析失败的事件的回调函数 */ callback: t.OffLocalServiceResolveFailCallback): void; offPageNotFound( /** 小程序要打开的页面不存在事件的回调函数 */ callback: t.OffPageNotFoundCallback): void; offWindowResize( /** 窗口尺寸变化事件的回调函数 */ callback: t.OffWindowResizeCallback): void; onAccelerometerChange( /** 加速度数据事件的回调函数 */ callback: t.OnAccelerometerChangeCallback): void; onAppHide( /** 小程序切后台事件的回调函数 */ callback: t.OnAppHideCallback): void; onAppShow( /** 小程序切前台事件的回调函数 */ callback: t.OnAppShowCallback): void; onAudioInterruptionBegin( /** 音频因为受到系统占用而被中断开始事件的回调函数 */ callback: t.OnAudioInterruptionBeginCallback): void; onAudioInterruptionEnd( /** 音频中断结束事件的回调函数 */ callback: t.OnAudioInterruptionEndCallback): void; onBLECharacteristicValueChange( /** 低功耗蓝牙设备的特征值变化事件的回调函数 */ callback: t.OnBLECharacteristicValueChangeCallback): void; onBLEConnectionStateChange( /** 低功耗蓝牙连接状态的改变事件的回调函数 */ callback: t.OnBLEConnectionStateChangeCallback): void; onBackgroundAudioPause( /** 音乐暂停事件的回调函数 */ callback: t.OnBackgroundAudioPauseCallback): void; onBackgroundAudioPlay( /** 音乐播放事件的回调函数 */ callback: t.OnBackgroundAudioPlayCallback): void; onBackgroundAudioStop( /** 音乐停止事件的回调函数 */ callback: t.OnBackgroundAudioStopCallback): void; onBeaconServiceChange( /** iBeacon 服务状态变化事件的回调函数 */ callback: t.OnBeaconServiceChangeCallback): void; onBeaconUpdate( /** iBeacon 设备更新事件的回调函数 */ callback: t.OnBeaconUpdateCallback): void; onBluetoothAdapterStateChange( /** 蓝牙适配器状态变化事件的回调函数 */ callback: t.OnBluetoothAdapterStateChangeCallback): void; onBluetoothDeviceFound( /** 寻找到新设备的事件的回调函数 */ callback: t.OnBluetoothDeviceFoundCallback): void; onCompassChange( /** 罗盘数据变化事件的回调函数 */ callback: t.OnCompassChangeCallback): void; onDeviceMotionChange( /** 设备方向变化事件的回调函数 */ callback: t.OnDeviceMotionChangeCallback): void; onError( /** 小程序错误事件的回调函数 */ callback: t.OnAppErrorCallback): void; onGetWifiList( /** 获取到 Wi-Fi 列表数据事件的回调函数 */ callback: t.OnGetWifiListCallback): void; onGyroscopeChange( /** 陀螺仪数据变化事件的回调函数 */ callback: t.OnGyroscopeChangeCallback): void; onHCEMessage( /** 接收 NFC 设备消息事件的回调函数 */ callback: t.OnHCEMessageCallback): void; onLocalServiceDiscoveryStop( /** mDNS 服务停止搜索的事件的回调函数 */ callback: t.OnLocalServiceDiscoveryStopCallback): void; onLocalServiceFound( /** mDNS 服务发现的事件的回调函数 */ callback: t.OnLocalServiceFoundCallback): void; onLocalServiceLost( /** mDNS 服务离开的事件的回调函数 */ callback: t.OnLocalServiceLostCallback): void; onLocalServiceResolveFail( /** mDNS 服务解析失败的事件的回调函数 */ callback: t.OnLocalServiceResolveFailCallback): void; onMemoryWarning( /** 内存不足告警事件的回调函数 */ callback: t.OnMemoryWarningCallback): void; onNetworkStatusChange( /** 网络状态变化事件的回调函数 */ callback: t.OnNetworkStatusChangeCallback): void; onPageNotFound( /** 小程序要打开的页面不存在事件的回调函数 */ callback: t.OnPageNotFoundCallback): void; onSocketClose( /** WebSocket 连接关闭事件的回调函数 */ callback: t.OnSocketCloseCallback): void; onSocketError( /** WebSocket 错误事件的回调函数 */ callback: t.OnSocketErrorCallback): void; onSocketMessage( /** WebSocket 接受到服务器的消息事件的回调函数 */ callback: t.OnSocketMessageCallback): void; onSocketOpen( /** WebSocket 连接打开事件的回调函数 */ callback: t.OnSocketOpenCallback): void; onUserCaptureScreen( /** 用户主动截屏事件的回调函数 */ callback: t.OnUserCaptureScreenCallback): void; onWifiConnected( /** 连接上 Wi-Fi 的事件的回调函数 */ callback: t.OnWifiConnectedCallback): void; onWindowResize( /** 窗口尺寸变化事件的回调函数 */ callback: t.OnWindowResizeCallback): void; openBluetoothAdapter(option?: t.OpenBluetoothAdapterOption): void; openCard(option: t.OpenCardOption): void; openDocument(option: t.OpenDocumentOption): void; openLocation(option: t.OpenLocationOption): void; openSetting(option?: t.OpenSettingOption): void; pageScrollTo(option: t.PageScrollToOption): void; pauseBackgroundAudio(option?: t.PauseBackgroundAudioOption): void; pauseVoice(option?: t.PauseVoiceOption): void; playBackgroundAudio(option: t.PlayBackgroundAudioOption): void; playVoice(option: t.PlayVoiceOption): void; previewImage(option: t.PreviewImageOption): void; reLaunch(option: t.ReLaunchOption): void; readBLECharacteristicValue(option: t.ReadBLECharacteristicValueOption): void; redirectTo(option: t.RedirectToOption): void; removeSavedFile(option: t.WxRemoveSavedFileOption): void; removeStorage(option: t.RemoveStorageOption): void; removeStorageSync( /** 本地缓存中指定的 key */ key: string): void; removeTabBarBadge(option: t.RemoveTabBarBadgeOption): void; reportAnalytics( /** 事件名 */ eventName: string, /** 上报的自定义数据。 */ data: t.Data): void; reportMonitor( /** 监控ID,在「小程序管理后台」新建数据指标后获得 */ name: string, /** 上报数值,经处理后会在「小程序管理后台」上展示每分钟的上报总量 */ value: number): void; requestPayment(option: t.RequestPaymentOption): void; saveFile(option: t.WxSaveFileOption): void; saveImageToPhotosAlbum(option: t.SaveImageToPhotosAlbumOption): void; saveVideoToPhotosAlbum(option: t.SaveVideoToPhotosAlbumOption): void; scanCode(option: t.ScanCodeOption): void; seekBackgroundAudio(option: t.SeekBackgroundAudioOption): void; sendHCEMessage(option: t.SendHCEMessageOption): void; sendSocketMessage(option: t.SendSocketMessageOption): void; setBackgroundColor(option: t.SetBackgroundColorOption): void; setBackgroundTextStyle(option: t.SetBackgroundTextStyleOption): void; setClipboardData(option: t.SetClipboardDataOption): void; setEnableDebug(option: t.SetEnableDebugOption): void; setInnerAudioOption(option: t.SetInnerAudioOption): void; setKeepScreenOn(option: t.SetKeepScreenOnOption): void; setNavigationBarColor(option: t.SetNavigationBarColorOption): void; setNavigationBarTitle(option: t.SetNavigationBarTitleOption): void; setScreenBrightness(option: t.SetScreenBrightnessOption): void; setStorage(option: t.SetStorageOption): void; setStorageSync( /** 本地缓存中指定的 key */ key: string, /** 需要存储的内容。只支持原生类型、Date、及能够通过`JSON.stringify`序列化的对象。 */ data: any): void; setTabBarBadge(option: t.SetTabBarBadgeOption): void; setTabBarItem(option: t.SetTabBarItemOption): void; setTabBarStyle(option: t.SetTabBarStyleOption): void; setTopBarText(option: t.SetTopBarTextOption): void; setWifiList(option: t.SetWifiListOption): void; showActionSheet(option: t.ShowActionSheetOption): void; showLoading(option: t.ShowLoadingOption): void; showModal(option: t.ShowModalOption): void; showNavigationBarLoading(option?: t.ShowNavigationBarLoadingOption): void; showShareMenu(option: t.ShowShareMenuOption): void; showTabBar(option: t.ShowTabBarOption): void; showTabBarRedDot(option: t.ShowTabBarRedDotOption): void; showToast(option: t.ShowToastOption): void; startAccelerometer(option: t.StartAccelerometerOption): void; startBeaconDiscovery(option: t.StartBeaconDiscoveryOption): void; startBluetoothDevicesDiscovery(option: t.StartBluetoothDevicesDiscoveryOption): void; startCompass(option?: t.StartCompassOption): void; startDeviceMotionListening(option: t.StartDeviceMotionListeningOption): void; startGyroscope(option: t.StartGyroscopeOption): void; startHCE(option: t.StartHCEOption): void; startLocalServiceDiscovery(option: t.StartLocalServiceDiscoveryOption): void; startPullDownRefresh(option?: t.StartPullDownRefreshOption): void; startRecord(option: t.WxStartRecordOption): void; startSoterAuthentication(option: t.StartSoterAuthenticationOption): void; startWifi(option?: t.StartWifiOption): void; stopAccelerometer(option?: t.StopAccelerometerOption): void; stopBackgroundAudio(option?: t.StopBackgroundAudioOption): void; stopBeaconDiscovery(option?: t.StopBeaconDiscoveryOption): void; stopBluetoothDevicesDiscovery(option?: t.StopBluetoothDevicesDiscoveryOption): void; stopCompass(option?: t.StopCompassOption): void; stopDeviceMotionListening(option?: t.StopDeviceMotionListeningOption): void; stopGyroscope(option?: t.StopGyroscopeOption): void; stopHCE(option?: t.StopHCEOption): void; stopLocalServiceDiscovery(option?: t.StopLocalServiceDiscoveryOption): void; stopPullDownRefresh(option?: t.StopPullDownRefreshOption): void; stopRecord(): void; stopVoice(option?: t.StopVoiceOption): void; stopWifi(option?: t.StopWifiOption): void; switchTab(option: t.SwitchTabOption): void; updateShareMenu(option: t.UpdateShareMenuOption): void; vibrateLong(option?: t.VibrateLongOption): void; vibrateShort(option?: t.VibrateShortOption): void; writeBLECharacteristicValue(option: t.WriteBLECharacteristicValueOption): void; clearInterval(intervalID: number): void; clearTimeout(timeoutID: number): void; setInterval( /** 回调函数 */ callback: Function, /** 执行回调函数之间的时间间隔,单位 ms。 */ delay?: number, /** param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。 */ rest?: any): number; setTimeout( /** 回调函数 */ callback: Function, /** 延迟的时间,函数的调用会在该延迟之后发生,单位 ms。 */ delay?: number, /** param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。 */ rest?: any): number; }
the_stack
import { SourceFile, Node, TextContentNode, Token } from "./nodes"; import { Position } from "./types"; import { isTextContentKind, isTokenKind, SyntaxKind, tokenToString } from "./tokens"; import { Scanner } from "./scanner"; import { NullDiagnosticMessages } from "./diagnostics"; const perFileLeadingTokensMap = new WeakMap<SourceFile, Map<Node, readonly Token[] | null>>(); const perFileTrailingTokensMap = new WeakMap<SourceFile, Map<Node, readonly Token[] | null>>(); /** * Navigates the syntax-tree of a {@link SourceFile}. * {@docCategory Compiler} * * @remarks * Nodes in Grammarkdown's syntax tree are immutable and do not maintain pointers to their parents. * This can make traversing through a document somewhat difficult. The NodeNavigator class is intended * to improve this process by providing an API that can traverse a syntax tree starting from the root. * * A NodeNavigator focuses on a specific {@link Node} within a syntax tree, and maintains the * path to that node from the root. Various methods on the navigator move the focus, allowing you to * navigate to any other node within the syntax tree. */ export class NodeNavigator { private _sourceFile: SourceFile; private _nodeStack: (Node | undefined)[]; private _edgeStack: (number | undefined)[]; private _arrayStack: (ReadonlyArray<Node> | undefined)[]; private _offsetStack: (number | undefined)[]; private _currentDepth: number; private _currentNode!: Node; private _currentEdge!: number; private _currentOffset!: number; private _currentArray: ReadonlyArray<Node> | undefined; private _parentNode: Node | undefined; private _hasAnyChildren: boolean | undefined; private _leadingTokens: readonly Token[] | undefined | null; private _trailingTokens: readonly Token[] | undefined | null; private _tokenOffset: number; private _copyOnNavigate: boolean = false; /** * @param sourceFile The {@link SourceFile} to use as the root of the navigator. */ public constructor(sourceFile: SourceFile); /** * @param other A {@link NodeNavigator} whose position information is used to create this navigator. */ public constructor(other: NodeNavigator); public constructor(sourceFileOrNavigator: SourceFile | NodeNavigator) { if (sourceFileOrNavigator instanceof NodeNavigator) { const navigator = <NodeNavigator>sourceFileOrNavigator; this._sourceFile = navigator._sourceFile; this._edgeStack = navigator._edgeStack.slice(); this._arrayStack = navigator._arrayStack.slice(); this._offsetStack = navigator._offsetStack.slice(); this._nodeStack = navigator._nodeStack.slice(); this._currentDepth = this._nodeStack.length - 1; this._leadingTokens = navigator._leadingTokens; this._trailingTokens = navigator._trailingTokens; this._tokenOffset = navigator._tokenOffset; } else { this._sourceFile = <SourceFile>sourceFileOrNavigator; this._edgeStack = [-1]; this._arrayStack = [undefined]; this._offsetStack = [0]; this._nodeStack = [this._sourceFile]; this._currentDepth = 0; this._leadingTokens = undefined; this._trailingTokens = undefined; this._tokenOffset = -1; } this._afterNavigate(); } /** * Creates a copy of this {@link NodeNavigator} at the same position. */ public clone() { return new NodeNavigator(this); } /** * Gets the root {@link SourceFile} node for this navigator. */ public getRoot() { return this._sourceFile; } /** * Gets the parent {@link Node} of the {@link Node} the navigator is currently focused on. */ public getParent() { return this._parentNode; } /** * Gets the {@link Node} the navigator is currently focused on. */ public getNode() { return this._currentNode; } /** * If the {@link Node} the navigator is currently focused on is a {@link TextContentNode}, returns the `text` of the node; * Otherwise, returns `undefined`. */ public getTextContent() { if (isTextContentKind(this.getKind())) { return (this._currentNode as TextContentNode).text; } } /** * Gets the {@link SyntaxKind} of the {@link Node} the navigator is currently focused on. */ public getKind() { return this._currentNode.kind; } /** * Gets the string representation of the {@link SyntaxKind} of the {@link Node} the navigator is currently focused on. */ public getKindString() { return tokenToString(this.getKind()); } /** * Gets the name of the property on the parent {@link Node} the navigator is currently focused on. */ public getName() { return this._leadingTokens ? "(leadingTokens)" : this._trailingTokens ? "(trailingTokens)" : this._parentNode?.edgeName(this._currentEdge); } /** * Gets the containing node array of {@link Node} the navigator is currently focused on. */ public getArray() { return this._leadingTokens || this._trailingTokens || this._currentArray; } /** * Gets the ordinal offset within the containing node array of {@link Node} the navigator is currently focused on. */ public getOffset() { return this._leadingTokens || this._trailingTokens ? this._tokenOffset : this._currentOffset; } /** * Gets the current depth within the syntax-tree of the current focus of the navigator. */ public getDepth() { return this._getDepth(); } /** * Returns a value indicating whether the focus of the navigator points to a {@link Node} in an array. */ public isArray(): boolean { return this._leadingTokens !== undefined || this._trailingTokens !== undefined || this._currentArray !== undefined; } /** * Returns a value indicating whether the navigator is focused on a leading token of the actual current node. */ public isLeadingToken() { return !!this._leadingTokens; } /** * Returns a value indicating whether the navigator is focused on a trailing token of the actual current node. */ public isTrailingToken() { return !!this._trailingTokens; } /** * Returns a value indicating whether the focus of the navigator points to either a {@link Token}, {@link TextContentNode}, or {@link InvalidSymbol} (as long as that `InvalidSymbol` has no trailing tokens). */ public isToken(): boolean { const kind = this.getKind(); return isTokenKind(kind) || isTextContentKind(kind) || !!this._leadingTokens || !!this._trailingTokens || kind === SyntaxKind.InvalidSymbol && !(scanInterveningTokens(this._currentNode, this._sourceFile), getTrailingTokens(this._currentNode, this._sourceFile)); } /** * Creates an iterator for the ancestors of the focused {@link Node}. * @param predicate An optional callback that can be used to filter the ancestors of the node. */ public ancestors(predicate?: (ancestor: Node) => boolean): IterableIterator<Node>; /** * Creates an iterator for the parse tree ancestors of the focused {@link Node}. * @param kind The {@link SyntaxKind} that any yielded ancestor must match. */ public ancestors(kind: SyntaxKind): IterableIterator<Node>; public * ancestors(predicateOrKind?: SyntaxKind | ((ancestor: Node) => boolean)): IterableIterator<Node> { const navigator = this.clone(); while (navigator.moveToParent()) { if (matchPredicateOrKind(navigator._currentNode, predicateOrKind)) yield navigator._currentNode; } } /** * Creates an iterator for the parse tree children of the focused {@link Node}. * @param predicate An optional callback that can be used to filter the children of the node. * @remarks This does not account for tokens not included in the parse tree. */ public children(predicate?: (child: Node) => boolean): IterableIterator<Node>; /** * Creates an iterator for the parse tree children of the focused {@link Node}. * @param kind The {@link SyntaxKind} that any yielded child must match. * @remarks This does not account for tokens not included in the parse tree. */ public children(kind: SyntaxKind): IterableIterator<Node>; public * children(predicateOrKind?: SyntaxKind | ((child: Node) => boolean)): IterableIterator<Node> { const navigator = this.clone(); if (navigator.moveToFirstChild()) { do { if (matchPredicateOrKind(navigator._currentNode, predicateOrKind)) yield navigator._currentNode; } while (navigator.moveToNextSibling()); } } /** * Creates an iterator for the tokens of the focused {@link Node}. * @param predicate An optional callback that can be used to filter the tokens of the node. */ public tokens(predicate?: (token: Node) => boolean): IterableIterator<Node>; /** * Creates an iterator for the tokens of the focused {@link Node}. * @param kind The {@link SyntaxKind} that any yielded token must match. */ public tokens(kind: SyntaxKind): IterableIterator<Node>; public * tokens(predicateOrKind?: SyntaxKind | ((child: Node) => boolean)): IterableIterator<Node> { const navigator = this.clone(); if (navigator.moveToFirstToken()) { do { if (matchPredicateOrKind(navigator._currentNode, predicateOrKind)) yield navigator._currentNode; } while (navigator.moveToNextToken()); } } /** * Determines whether the focused {@link Node} has an ancestor that matches the supplied predicate. * @param predicate An optional callback used to filter the ancestors of the node. * @returns `true` if the focused {@link Node} contains an ancestor that matches the supplied predicate; otherwise, `false`. */ public hasAncestor(predicate?: (ancestor: Node) => boolean): boolean; /** * Determines whether the focused {@link Node} has an ancestor that matches the supplied predicate. * @param predicate An optional callback used to filter the ancestors of the node. * @returns `true` if the focused {@link Node} contains an ancestor that matches the supplied predicate; otherwise, `false`. */ public hasAncestor(kind: SyntaxKind): boolean; public hasAncestor(predicateOrKind?: SyntaxKind | ((ancestor: Node) => boolean)): boolean { for (let nextDepth = this._getDepth() - 1; nextDepth >= 0; nextDepth--) { const nextNode = this._nodeStack[nextDepth]!; if (matchPredicateOrKind(nextNode, predicateOrKind)) { return true; } } return false; } /** * Determines whether the focused {@link Node} has any children that match the supplied predicate. * @param predicate An optional callback that can be used to filter the children of the node. * @returns `true` if the focused {@link Node} contains a child that matches the supplied predicate; otherwise, `false`. * @remarks This does not account for tokens not included in the parse tree. */ public hasChildren(predicate?: (child: Node) => boolean): boolean; /** * Determines whether the focused {@link Node} has any children with the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that at least one child must match. * @returns `true` if the focused {@link Node} contains a matching child; otherwise, `false`. * @remarks This does not account for tokens not included in the parse tree. */ public hasChildren(kind: SyntaxKind): boolean; public hasChildren(predicateOrKind?: SyntaxKind | ((child: Node) => boolean)): boolean { if (this._hasAnyChildren === false || this._currentNode.edgeCount === 0) { return false; } if (predicateOrKind === undefined && this._hasAnyChildren !== undefined) { return this._hasAnyChildren; } for (let nextEdge = 0; nextEdge < this._currentNode.edgeCount; nextEdge++) { const next = this._currentNode.edgeValue(nextEdge); if (isNodeArray(next)) { for (let nextOffset = 0; nextOffset < next.length; nextOffset++) { const nextNode = next[nextOffset]; if (nextNode && matchPredicateOrKind(nextNode, predicateOrKind)) { return this._hasAnyChildren = true; } } } else if (next && matchPredicateOrKind(next, predicateOrKind)) { return this._hasAnyChildren = true; } } if (!predicateOrKind) { this._hasAnyChildren = false; } return false; } /** * Determines whether the focused {@link Node} matches the supplied predicate. * @param predicate A callback used to match the focused {@link Node}. * @returns `true` if the focused {@link Node} matches; otherwise, `false`. */ public isMatch(predicate: (node: Node) => boolean): boolean; /** * Determines whether the focused {@link Node} matches the supplied {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the focused {@link Node} must match. * @returns `true` if the focused {@link Node} matches; otherwise, `false`. */ public isMatch(kind: SyntaxKind): boolean; public isMatch(predicateOrKind: SyntaxKind | ((node: Node) => boolean)): boolean { return this._isMatch(predicateOrKind); } /** * Determines whether this navigator is focused on the same location within the tree as another navigator. * @param other The other navigator. * @returns `true` if both navigators are focused on the same location within the tree; otherwise, `false`. */ public isSamePosition(other: NodeNavigator) { if (this === other) { return true; } return this._sourceFile === other._sourceFile && this._currentDepth === other._currentDepth && this._currentEdge === other._currentEdge && this._currentArray === other._currentArray && this._currentOffset === other._currentOffset && this._currentNode === other._currentNode && this._leadingTokens === other._leadingTokens && this._trailingTokens === other._trailingTokens && this._tokenOffset === other._tokenOffset; } /** * Moves the focus of this navigator to the same position within the syntax tree as another navigator. * @param other The other navigator. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveTo(other: NodeNavigator) { if (this === other) { return true; } if (this._sourceFile !== other._sourceFile) { return false; } this._currentDepth = other._currentDepth; this._edgeStack = other._edgeStack.slice(); this._arrayStack = other._arrayStack.slice(); this._offsetStack = other._offsetStack.slice(); this._nodeStack = other._nodeStack.slice(); this._leadingTokens = other._leadingTokens; this._trailingTokens = other._trailingTokens; this._tokenOffset = other._tokenOffset; this._afterNavigate(); return true; } /** * Moves the focus of the navigator to the root of the syntax tree. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToRoot(): boolean { if (this._getDepth() > 0) { this._beforeNavigate(); this._reset(); this._afterNavigate(); } return true; } /** * Moves the focus of the navigator to the parent {@link Node} of the focused {@link Node}. * @param predicate An optional callback that determines whether the focus should move to the parent node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToParent(predicate?: (parent: Node) => boolean): boolean; /** * Moves the focus of the navigator to the parent {@link Node} of the focused {@link Node}. * @param kind The required {@link SyntaxKind} of the parent node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToParent(kind: SyntaxKind): boolean; public moveToParent(predicateOrKind?: SyntaxKind | ((node: Node) => boolean)): boolean { if (this._getDepth() > 0) { if (matchPredicateOrKind(this._parentNode!, predicateOrKind)) { this._beforeNavigate(); this._popEdge(); this._afterNavigate(); return true; } } return false; } /** * Moves the focus of the navigator to the nearest ancestor matching the supplied predicate. If the current node * matches the predicate, the focus does not change. * @param predicate A callback used to match an ancestor. * @returns `true` if the current node matched the predicate or the navigator's focus changed; otherwise, `false`. */ public moveToAncestorOrSelf(predicate: (ancestorOrSelf: Node) => boolean): boolean; /** * Moves the focus of the navigator to the nearest ancestor matching the supplied predicate. If the current node * matches the predicate, the focus does not change. * @param kind The {@link SyntaxKind} that the focused {@link Node} or one of its ancestors must match. * @returns `true` if the current node matched the predicate or the navigator's focus changed; otherwise, `false`. */ public moveToAncestorOrSelf(kind: SyntaxKind): boolean; public moveToAncestorOrSelf(predicateOrKind: SyntaxKind | ((node: Node) => boolean)): boolean { return this._isMatch(predicateOrKind as SyntaxKind) || this.moveToAncestor(predicateOrKind as SyntaxKind); } /** * Moves the focus of the navigator to the nearest ancestor matching the supplied predicate. * @param predicate A callback used to match an ancestor. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToAncestor(predicate: (ancestor: Node) => boolean): boolean; /** * Moves the focus of the navigator to the nearest ancestor matching the supplied {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the ancestor must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToAncestor(kind: SyntaxKind): boolean; public moveToAncestor(predicateOrKind: SyntaxKind | ((node: Node) => boolean)): boolean { for (let nextDepth = this._getDepth() - 1; nextDepth >= 0; nextDepth--) { const nextNode = this._nodeStack[nextDepth]!; if (matchPredicateOrKind(nextNode, predicateOrKind)) { this._beforeNavigate(); while (this._getDepth() !== nextDepth) { this._popEdge(); } this._afterNavigate(); return true; } } return false; } /** * Moves the focus of the navigator to the parent of the focused {@link Node} if that parent is a {@link SourceElement}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToSourceElement(): boolean { return this.moveToParent(matchSourceElement); } /** * Moves the focus of the navigator to the parent of the focused {@link Node} if that parent is either a {@link Parameter} or a {@link Production}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToDeclaration(): boolean { return this.moveToParent(SyntaxKind.Parameter) || this.moveToParent(SyntaxKind.Production); } /** * Moves the focus of the navigator to the nearest {@link Identifier}. * @returns `true` if the current node is an {@link Identifier} or the navigator's focus changed; otherwise, `false`. * @remarks * The "nearest {@link Identifier}" is determined using the following rules: * <ul> * <li>If the focus or its nearest ancestor is a {@link Parameter}, move to the `name` of the {@link Parameter}.</li> * <li>If the focus or its nearest ancestor is an {@link Argument}, move to the `name` of the {@link Argument}.</li> * <li>If the focus or its nearest ancestor is a {@link Nonterminal}, move to the `name` of the {@link Nonterminal}.</li> * <li>If the focus or its nearest ancestor is a {@link LexicalGoalAssertion}, move to the `symbol` of the of the {@link LexicalGoalAssertion}.</li> * <li>If the focus or its nearest ancestor is a {@link Define}, move to the `key` of the {@link Define}.</li> * <li>If the focus or its nearest ancestor is a {@link Constraints}, move to the `name` of the of the first {@link Argument} of the {@link Constraints}.</li> * <li>If the focus is not within the `body` of a {@link Production} and the focus or its nearest ancestor is a {@link Production}, move to the `name` of the {@link Production}.</li> * </ul> */ public moveToName(): boolean { if (this.getKind() === SyntaxKind.Identifier) { return true; } else { const navigator = this.clone(); if (navigator.moveToAncestorOrSelf(SyntaxKind.Parameter) && navigator.moveToFirstChild("name")) { return this.moveTo(navigator); } navigator.moveTo(this); if (navigator.moveToAncestorOrSelf(SyntaxKind.Argument) && navigator.moveToFirstChild("name")) { return this.moveTo(navigator); } navigator.moveTo(this); if (navigator.moveToAncestorOrSelf(SyntaxKind.Nonterminal) && navigator.moveToFirstChild("name")) { return this.moveTo(navigator); } navigator.moveTo(this); if (navigator.moveToAncestorOrSelf(SyntaxKind.LexicalGoalAssertion) && navigator.moveToFirstChild("symbol")) { return this.moveTo(navigator); } navigator.moveTo(this); if (navigator.moveToAncestorOrSelf(SyntaxKind.Constraints) && navigator.moveToFirstChild("elements") && navigator.moveToFirstChild("name")) { return this.moveTo(navigator); } navigator.moveTo(this); if (!navigator.hasAncestor(matchProductionBody) && navigator.moveToAncestorOrSelf(SyntaxKind.Production) && navigator.moveToFirstChild("name")) { return this.moveTo(navigator); } navigator.moveTo(this); if (navigator.moveToParent(SyntaxKind.InvalidAssertion) && navigator.moveToParent(SyntaxKind.SymbolSpan) && navigator.moveToPreviousSibling(SyntaxKind.Nonterminal) && navigator.moveToFirstChild("name")) { return this.moveTo(navigator); } } return false; } /** * Moves the focus of the navigator to the first child of the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToFirstChild(): boolean; /** * Moves the focus of the navigator to the first child of the focused {@link Node} with the provided property name. * @param name The name of the property on the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToFirstChild(name: string): boolean; /** * Moves the focus of the navigator to the first child of the focused {@link Node} matching the supplied predicate. * @param predicate A callback used to match a child node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToFirstChild(predicate: (child: Node) => boolean): boolean; /** * Moves the focus of the navigator to the first child of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the child must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToFirstChild(kind: SyntaxKind): boolean; public moveToFirstChild(predicateOrNameOrKind?: string | SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToChild(Navigation.first, Navigation.next, predicateOrNameOrKind, /*speculative*/ false); } /** * Moves the focus of the navigator to the last child of the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToLastChild(): boolean; /** * Moves the focus of the navigator to the last child of the focused {@link Node} with the provided property name. * @param name The name of the property on the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToLastChild(name: string): boolean; /** * Moves the focus of the navigator to the last child of the focused {@link Node} matching the supplied predicate. * @param predicate A callback used to match a child node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToLastChild(predicate: (node: Node) => boolean): boolean; /** * Moves the focus of the navigator to the last child of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the child must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToLastChild(kind: SyntaxKind): boolean; public moveToLastChild(predicateOrNameOrKind?: string | SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToChild(Navigation.last, Navigation.previous, predicateOrNameOrKind, /*speculative*/ false); } /** * Moves the focus of the navigator to the first element of the containing array of the focused {@link Node} matching the supplied predicate. * @param predicate A callback used to match a node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToFirstElement(predicate?: (element: Node) => boolean): boolean; /** * Moves the focus of the navigator to the first element of the containing array of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the element must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToFirstElement(kind: SyntaxKind): boolean; public moveToFirstElement(predicateOrKind?: SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToElement(Navigation.first, Navigation.next, this._currentEdge, this._currentArray, this._currentOffset, predicateOrKind, /*speculative*/ false); } /** * Moves the focus of the navigator to the previous element in the containing array of the focused {@link Node} matching the supplied predicate. * @param predicate A callback used to match a node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToPreviousElement(predicate?: (node: Node) => boolean): boolean; /** * Moves the focus of the navigator to the previous element in the containing array of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the element must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToPreviousElement(kind: SyntaxKind): boolean; public moveToPreviousElement(predicateOrKind?: SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToElement(Navigation.previous, Navigation.previous, this._currentEdge, this._currentArray, this._currentOffset, predicateOrKind, /*speculative*/ false); } /** * Moves the focus of the navigator to the next element in the containing array of the focused {@link Node} matching the supplied predicate. * @param predicate A callback used to match a node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToNextElement(predicate?: (node: Node) => boolean): boolean; /** * Moves the focus of the navigator to the next element in the containing array of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the element must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToNextElement(kind: SyntaxKind): boolean; public moveToNextElement(predicateOrKind?: SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToElement(Navigation.next, Navigation.next, this._currentEdge, this._currentArray, this._currentOffset, predicateOrKind, /*speculative*/ false); } /** * Moves the focus of the navigator to the last element of the containing array of the focused {@link Node} matching the supplied predicate. * @param predicate A callback used to match a node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToLastElement(predicate?: (node: Node) => boolean): boolean; /** * Moves the focus of the navigator to the last element of the containing array of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the element must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToLastElement(kind: SyntaxKind): boolean; public moveToLastElement(predicateOrKind?: SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToElement(Navigation.last, Navigation.previous, this._currentEdge, this._currentArray, this._currentOffset, predicateOrKind, /*speculative*/ false); } /** * Moves the focus of the navigator to the first sibling of the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToFirstSibling(): boolean; /** * Moves the focus of the navigator to the first sibling of the focused {@link Node} with the provided property name. * @param name The name of a property on the parent of the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToFirstSibling(name: string): boolean; /** * Moves the focus of the navigator to the first sibling of the focused {@link Node} that matches the provided predicate. * @param predicate A callback used to match a sibling node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToFirstSibling(predicate: (sibling: Node) => boolean): boolean; /** * Moves the focus of the navigator to the first sibling of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the sibling must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToFirstSibling(kind: SyntaxKind): boolean; public moveToFirstSibling(predicateOrNameOrKind?: string | SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToSibling(Navigation.first, undefined, Navigation.first, Navigation.next, this._parentNode, predicateOrNameOrKind, /*speculative*/ false); } /** * Moves the focus of the navigator to the previous sibling of the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToPreviousSibling(): boolean; /** * Moves the focus of the navigator to the previous sibling of the focused {@link Node} with the provided property name. * @param name The name of a property on the parent of the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToPreviousSibling(name: string): boolean; /** * Moves the focus of the navigator to the previous sibling of the focused {@link Node} that matches the provided predicate. * @param predicate A callback used to match a sibling node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToPreviousSibling(predicate: (sibling: Node) => boolean): boolean; /** * Moves the focus of the navigator to the previous sibling of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the sibling must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToPreviousSibling(kind: SyntaxKind): boolean; public moveToPreviousSibling(predicateOrNameOrKind?: string | SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToSibling(Navigation.previous, Navigation.previous, Navigation.last, Navigation.previous, this._parentNode, predicateOrNameOrKind, /*speculative*/ false); } /** * Tests whether the navigator can move the focus of the navigator to the previous sibling of the focused {@link Node}. * @returns `true` if the navigator's focus can change; otherwise, `false`. */ public hasPreviousSibling(): boolean; /** * Tests whether the navigator can move the focus of the navigator to the previous sibling of the focused {@link Node} with the provided property name. * @param name The name of a property on the parent of the focused {@link Node}. * @returns `true` if the navigator's focus can change; otherwise, `false`. */ public hasPreviousSibling(name: string): boolean; /** * Tests whether the navigator can move the focus of the navigator to the previous sibling of the focused {@link Node} that matches the provided predicate. * @param predicate A callback used to match a sibling node. * @returns `true` if the navigator's focus can change; otherwise, `false`. */ public hasPreviousSibling(predicate: (sibling: Node) => boolean): boolean; /** * Tests whether the navigator can move the focus of the navigator to the previous sibling of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the sibling must match. * @returns `true` if the navigator's focus can change; otherwise, `false`. */ public hasPreviousSibling(kind: SyntaxKind): boolean; public hasPreviousSibling(predicateOrNameOrKind?: string | SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToSibling(Navigation.previous, Navigation.previous, Navigation.last, Navigation.previous, this._parentNode, predicateOrNameOrKind, /*speculative*/ true); } /** * Moves the focus of the navigator to the next sibling of the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToNextSibling(): boolean; /** * Moves the focus of the navigator to the next sibling of the focused {@link Node} with the provided property name. * @param name The name of a property on the parent of the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToNextSibling(name: string): boolean; /** * Moves the focus of the navigator to the next sibling of the focused {@link Node} that matches the provided predicate. * @param predicate A callback used to match a sibling node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToNextSibling(predicate: (node: Node) => boolean): boolean; /** * Moves the focus of the navigator to the next sibling of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the sibling must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToNextSibling(kind: SyntaxKind): boolean; public moveToNextSibling(predicateOrNameOrKind?: string | SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToSibling(Navigation.next, Navigation.next, Navigation.first, Navigation.next, this._parentNode, predicateOrNameOrKind, /*speculative*/ false); } /** * Tests whether the navigator can move the focus of the navigator to the next sibling of the focused {@link Node}. * @returns `true` if the navigator's focus can change; otherwise, `false`. */ public hasNextSibling(): boolean; /** * Tests whether the navigator can move the focus of the navigator to the next sibling of the focused {@link Node} with the provided property name. * @param name The name of a property on the parent of the focused {@link Node}. * @returns `true` if the navigator's focus can change; otherwise, `false`. */ public hasNextSibling(name: string): boolean; /** * Tests whether the navigator can move the focus of the navigator to the next sibling of the focused {@link Node} that matches the provided predicate. * @param predicate A callback used to match a sibling node. * @returns `true` if the navigator's focus can change; otherwise, `false`. */ public hasNextSibling(predicate: (node: Node) => boolean): boolean; /** * Tests whether the navigator can move the focus of the navigator to the next sibling of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the sibling must match. * @returns `true` if the navigator's focus can change; otherwise, `false`. */ public hasNextSibling(kind: SyntaxKind): boolean; public hasNextSibling(predicateOrNameOrKind?: string | SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToSibling(Navigation.next, Navigation.next, Navigation.first, Navigation.next, this._parentNode, predicateOrNameOrKind, /*speculative*/ true); } /** * Moves the focus of the navigator to the last sibling of the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToLastSibling(): boolean; /** * Moves the focus of the navigator to the last sibling of the focused {@link Node} with the provided property name. * @param name The name of a property on the parent of the focused {@link Node}. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToLastSibling(name: string): boolean; /** * Moves the focus of the navigator to the last sibling of the focused {@link Node} that matches the provided predicate. * @param predicate A callback used to match a sibling node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToLastSibling(predicate: (node: Node) => boolean): boolean; /** * Moves the focus of the navigator to the last sibling of the focused {@link Node} matching the provided {@link SyntaxKind}. * @param kind The {@link SyntaxKind} that the sibling must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToLastSibling(kind: SyntaxKind): boolean; public moveToLastSibling(predicateOrNameOrKind?: string | SyntaxKind | ((node: Node) => boolean)): boolean { return this._moveToSibling(Navigation.last, undefined, Navigation.last, Navigation.previous, this._parentNode, predicateOrNameOrKind, /*speculative*/ false); } /** * Moves the focus of the navigator to the first {@link Token}, {@link TextContent} or {@link InvalidSymbol} descendant (or self) of the focused {@link Node}. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToFirstToken(): boolean; /** * Moves the focus of the navigator to the first {@link Token}, {@link TextContent} or {@link InvalidSymbol} descendant (or self) of the focused {@link Node}. * @param predicate A callback used to match a token node. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToFirstToken(predicate: (node: Node) => boolean): boolean; /** * Moves the focus of the navigator to the first {@link Token}, {@link TextContent} or {@link InvalidSymbol} descendant (or self) of the focused {@link Node}. * @param kind The {@link SyntaxKind} that the previous token must match. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToFirstToken(kind: SyntaxKind): boolean; public moveToFirstToken(predicateOrKind?: SyntaxKind | ((node: Node) => boolean)) { return this._speculate(() => this._moveToFirstTokenWorker() && this._isMatch(predicateOrKind)); } /** * Moves the focus of the navigator to the last {@link Token}, {@link TextContent} or {@link InvalidSymbol} descendant (or self) of the focused {@link Node}. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToLastToken(): boolean; /** * Moves the focus of the navigator to the last {@link Token}, {@link TextContent} or {@link InvalidSymbol} descendant (or self) of the focused {@link Node}. * @param predicate A callback used to match a token node. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToLastToken(predicate: (node: Node) => boolean): boolean; /** * Moves the focus of the navigator to the last {@link Token}, {@link TextContent} or {@link InvalidSymbol} descendant (or self) of the focused {@link Node}. * @param kind The {@link SyntaxKind} that the previous token must match. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToLastToken(kind: SyntaxKind): boolean; public moveToLastToken(predicateOrKind?: SyntaxKind | ((node: Node) => boolean)) { return this._speculate(() => this._moveToLastTokenWorker() && this._isMatch(predicateOrKind)); } /** * Moves the focus of the navigator to the next {@link Token}, {@link TextContent} or {@link InvalidSymbol} following the focused {@link Node} in document order. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToNextToken(): boolean; /** * Moves the focus of the navigator to the next {@link Token}, {@link TextContent} or {@link InvalidSymbol} following the focused {@link Node} in document order. * @param predicate A callback used to match a token node. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToNextToken(predicate: (node: Node) => boolean): boolean; /** * Moves the focus of the navigator to the next {@link Token}, {@link TextContent} or {@link InvalidSymbol} following the focused {@link Node} in document order. * @param kind The {@link SyntaxKind} that the previous token must match. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToNextToken(kind: SyntaxKind): boolean; public moveToNextToken(predicateOrKind?: SyntaxKind | ((node: Node) => boolean)) { return this._speculate(() => this._moveToNextTokenWorker() && this._isMatch(predicateOrKind)); } /** * Moves the focus of the navigator to the previous {@link Token}, {@link TextContent} or {@link InvalidSymbol} preceding the focused {@link Node} in document order. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToPreviousToken(): boolean; /** * Moves the focus of the navigator to the previous {@link Token}, {@link TextContent} or {@link InvalidSymbol} preceding the focused {@link Node} in document order. * @param predicate A callback used to match a token node. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToPreviousToken(predicate: (node: Node) => boolean): boolean; /** * Moves the focus of the navigator to the previous {@link Token}, {@link TextContent} or {@link InvalidSymbol} preceding the focused {@link Node} in document order. * @param kind The {@link SyntaxKind} that the previous token must match. * @returns `true` if the current focus is a {@link Token}, {@link TextContent} or {@link InvalidSymbol} or if the navigator's focus changed; otherwise, `false`. */ public moveToPreviousToken(kind: SyntaxKind): boolean; public moveToPreviousToken(predicateOrKind?: SyntaxKind | ((node: Node) => boolean)) { return this._speculate(() => this._moveToPreviousTokenWorker() && this._isMatch(predicateOrKind)); } /** * Moves the focus of the navigator to the {@link Node} that contains the provided [Position](xref:grammarkdown!Position:interface). * @param position The [Position](xref:grammarkdown!Position:interface) at which to focus the navigator. * @param outermost When `true`, moves to the outermost node containing the provided position. * When `false` or not specified, moves to the innermost node containing the provided position. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToPosition(position: Position, outermost?: boolean) { const pos = this._sourceFile.lineMap.offsetAt(position); return this._speculate(() => { this.moveToRoot(); if (pos === 0) { if (outermost) { this.moveToFirstChild(); } else { this.moveToFirstToken(); } return true; } if (pos === this._sourceFile.text.length) { if (outermost) { this.moveToLastChild(); } else { this.moveToLastToken(); } return true; } if (this._moveToPositionWorker(pos, outermost)) { return true; } return false; }); } /** * Moves the focus of the navigator to the nearest {@link Token}, {@link TextContentNode}, or {@link InvalidSymbol} that is touching the provided [Position](xref:grammarkdown!Position:interface). * @param position The [Position](xref:grammarkdown!Position:interface) at which to focus the navigator. * @param predicate A callback used to match a token node. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToTouchingToken(position: Position, predicate?: SyntaxKind): boolean; /** * Moves the focus of the navigator to the nearest {@link Token}, {@link TextContentNode}, or {@link InvalidSymbol} that is touching the provided [Position](xref:grammarkdown!Position:interface). * @param position The [Position](xref:grammarkdown!Position:interface) at which to focus the navigator. * @param kind The {@link SyntaxKind} that the previous token must match. * @returns `true` if the navigator's focus changed; otherwise, `false`. */ public moveToTouchingToken(position: Position, kind: SyntaxKind): boolean; public moveToTouchingToken(position: Position, predicateOrKind?: SyntaxKind | ((node: Node) => boolean)): boolean { return this._speculate(() => this._moveToTouchingTokenWorker(position) && this._isMatch(predicateOrKind)); } private _isMatch(predicateOrKind?: SyntaxKind | ((node: Node) => boolean)): boolean { return matchPredicateOrKind(this._currentNode, predicateOrKind); } private _moveToPositionWorker(pos: number, outermost?: boolean) { if (pos >= this._currentNode.pos && pos < this._currentNode.end) { if (!outermost) { if (this.moveToFirstChild()) { do { if (this._moveToPositionWorker(pos)) { return true; } } while (this.moveToNextSibling()); this.moveToParent(); } } return true; } return false; } private _moveToTouchingTokenWorker(position: Position) { if (this.moveToPosition(position)) { // If the position is inside the trivia of the current node, move to the previous node. const tokenPosition = this._sourceFile.lineMap.positionAt(this._currentNode.getStart(this._sourceFile)); if (Position.compare(position, tokenPosition) < 0) { return this.moveToPreviousToken(); } return true; } return false; } private _moveToFirstLeadingToken() { if (this._parentNode) scanInterveningTokens(this._parentNode, this._sourceFile); const leadingTokens = getLeadingTokens(this._currentNode, this._sourceFile); if (leadingTokens) { this._beforeNavigate(); this._leadingTokens = leadingTokens; this._trailingTokens = undefined; this._tokenOffset = 0; this._afterNavigate(); return true; } return false; } private _moveToPreviousLeadingToken() { if (this._leadingTokens && this._tokenOffset > 0) { this._beforeNavigate(); this._tokenOffset--; this._afterNavigate(); return true; } return false; } private _moveToNextLeadingToken() { if (this._leadingTokens && this._tokenOffset < this._leadingTokens.length - 1) { this._beforeNavigate(); this._tokenOffset++; this._afterNavigate(); return true; } return false; } private _moveToLastLeadingToken() { if (this._parentNode) scanInterveningTokens(this._parentNode, this._sourceFile); const leadingTokens = getLeadingTokens(this._currentNode, this._sourceFile); if (leadingTokens) { this._beforeNavigate(); this._leadingTokens = leadingTokens; this._trailingTokens = undefined; this._tokenOffset = leadingTokens.length - 1; this._afterNavigate(); return true; } return false; } private _moveToFirstTrailingToken() { scanInterveningTokens(this._currentNode, this._sourceFile); const trailingTokens = getTrailingTokens(this._currentNode, this._sourceFile); if (trailingTokens) { this._beforeNavigate(); this._leadingTokens = undefined; this._trailingTokens = trailingTokens; this._tokenOffset = 0; this._afterNavigate(); return true; } return false; } private _moveToLastTrailingToken() { scanInterveningTokens(this._currentNode, this._sourceFile); const trailingTokens = getTrailingTokens(this._currentNode, this._sourceFile); if (trailingTokens) { this._beforeNavigate(); this._leadingTokens = undefined; this._trailingTokens = trailingTokens; this._tokenOffset = trailingTokens.length - 1; this._afterNavigate(); return true; } return false; } private _moveToPreviousTrailingToken() { if (this._trailingTokens && this._tokenOffset > 0) { this._beforeNavigate(); this._tokenOffset--; this._afterNavigate(); return true; } return false; } private _moveToNextTrailingToken() { if (this._trailingTokens && this._tokenOffset < this._trailingTokens.length - 1) { this._beforeNavigate(); this._tokenOffset++; this._afterNavigate(); return true; } return false; } private _moveToFirstTokenWorker() { // find the first token within the `pos` and `end` of the current node. while (!this.isToken()) { // not a token, try its children if (!this.moveToFirstChild()) { // no children, try trailing tokens... return this._moveToFirstTrailingToken(); } // found a child, try leading tokens... if (this._moveToFirstLeadingToken()) return true; // try again with the child... } return true; } private _moveToLastTokenWorker() { // find the last token within the `pos` and `end` of the current node while (!this.isToken()) { // not a token, try this node's trailing tokens... if (this._moveToLastTrailingToken()) return true; // no trailing tokens... if (!this.moveToLastChild()) return false; // no children, nothing else to try // try again with the child... } return true; } private _moveToNextTokenWorker() { if (this._leadingTokens) { if (this._moveToNextLeadingToken()) return true; // we got the next leading token // done processing leading tokens this._beforeNavigate(); this._leadingTokens = undefined; this._tokenOffset = -1; this._afterNavigate(); // we should now be on the node following the leading tokens return this._moveToFirstTokenWorker(); } else if (this._trailingTokens) { if (this._moveToNextTrailingToken()) return true; // we got the next trailing token // done processing trailing tokens this._beforeNavigate(); this._trailingTokens = undefined; this._tokenOffset = -1; this._afterNavigate(); // we should now be on the parent node containing the trailing tokens, // need to try with its next sibling... } // move to the next sibling of this node while (!this.moveToNextSibling()) { // no sibling, try parents... if (!this.moveToParent()) return false; // no parent, nothing else to try // found parent, try trailing tokens... if (this._moveToFirstTrailingToken()) return true; // moved to first trailing token // no trailing token, try next sibling of parent... } // we are at the next sibling, start with its leading tokens (if any) if (this._moveToFirstLeadingToken()) return true; // If we are here, we are in some node adjacent to the starting node return this._moveToFirstTokenWorker(); } private _moveToPreviousTokenWorker() { if (this._leadingTokens) { if (this._moveToPreviousLeadingToken()) return true; // we got the previous leading token // done processing leading tokens this._beforeNavigate(); this._leadingTokens = undefined; this._tokenOffset = -1; this._afterNavigate(); // we should now be on the node following the leading tokens, need to try with // the previous sibling... } else { if (this._trailingTokens) { if (this._moveToPreviousTrailingToken()) return true; // we got the previous trailing token // done processing trailing tokens this._beforeNavigate(); this._trailingTokens = undefined; this._tokenOffset = -1; this._afterNavigate(); // we should now be on the parent node containing the trailing tokens, need to try // with the last child... if (this.moveToLastChild()) { // move to the last token of the last child return this._moveToLastTokenWorker(); } } // current node is a token, move to any leading tokens if (this._moveToLastLeadingToken()) return true; // no leading tokens, need to try with the previous sibling... } while (!this.moveToPreviousSibling()) { // no sibling, try parents... if (!this.moveToParent()) return false; // no parent, nothing else to try // found parent, try leading tokens... if (this._moveToLastLeadingToken()) return true; // found leading token of parent // no leading token, try next sibling of parent... } // If we are here, we are in some node adjacent to the starting node return this._moveToLastTokenWorker(); } private _getDepth() { return (this._leadingTokens || this._trailingTokens) ? this._currentDepth + 1 : this._currentDepth; } private _speculate(cb: () => boolean) { const currentDepth = this._currentDepth; const edgeStack = this._edgeStack; const arrayStack = this._arrayStack; const offsetStack = this._offsetStack; const nodeStack = this._nodeStack; const hasChild = this._hasAnyChildren; const leadingTokens = this._leadingTokens; const trailingTokens = this._trailingTokens; const tokenOffset = this._tokenOffset; // The following nodes are set by _afterNavigate based on the saved information above: // this._currentEdge // this._currentArray // this._currentOffset // this._currentNode // this._parentNode this._copyOnNavigate = true; let result = false; try { result = cb(); } finally { if (!result) { this._currentDepth = currentDepth; this._edgeStack = edgeStack; this._arrayStack = arrayStack; this._offsetStack = offsetStack; this._nodeStack = nodeStack; this._hasAnyChildren = hasChild; this._leadingTokens = leadingTokens; this._trailingTokens = trailingTokens; this._tokenOffset = tokenOffset; this._afterNavigate(); } } return result; } private _beforeNavigate() { if (this._copyOnNavigate) { this._edgeStack = this._edgeStack.slice(); this._arrayStack = this._arrayStack.slice(); this._offsetStack = this._offsetStack.slice(); this._nodeStack = this._nodeStack.slice(); this._copyOnNavigate = false; } } private _afterNavigate() { this._currentEdge = this._edgeStack[this._currentDepth]!; this._currentArray = this._arrayStack[this._currentDepth]; this._currentOffset = this._offsetStack[this._currentDepth]!; this._currentNode = this._leadingTokens ? this._leadingTokens[this._tokenOffset] : this._trailingTokens ? this._trailingTokens[this._tokenOffset] : this._nodeStack[this._currentDepth]!; this._parentNode = (this._leadingTokens || this._trailingTokens) ? this._nodeStack[this._currentDepth] : this._currentDepth > 0 ? this._nodeStack[this._currentDepth - 1] : undefined; this._copyOnNavigate = false; } private _pushEdge() { this._edgeStack.push(undefined); this._arrayStack.push(undefined); this._offsetStack.push(undefined); this._nodeStack.push(undefined); this._hasAnyChildren = undefined; this._leadingTokens = undefined; this._trailingTokens = undefined; this._tokenOffset = -1; this._currentDepth++; } private _setEdge(edge: number, array: ReadonlyArray<Node> | undefined, offset: number | undefined, node: Node) { this._edgeStack[this._currentDepth] = edge; this._arrayStack[this._currentDepth] = array; this._offsetStack[this._currentDepth] = offset; this._nodeStack[this._currentDepth] = node; this._leadingTokens = undefined; this._trailingTokens = undefined; this._tokenOffset = -1; this._hasAnyChildren = undefined; } private _popEdge() { // if we have trailing tokens we are in a virtual edge. There's no need to reset the depth. if (this._trailingTokens) { this._trailingTokens = undefined; this._tokenOffset = -1; } else { this._currentDepth--; this._edgeStack.pop(); this._arrayStack.pop(); this._offsetStack.pop(); this._nodeStack.pop(); this._leadingTokens = undefined; this._tokenOffset = -1; this._hasAnyChildren = this._currentNode !== undefined; } } private _moveToChild(initializer: SeekOperation, seekDirection: SeekOperation, predicateOrNameOrKind: string | SyntaxKind | ((node: Node) => boolean) | undefined, speculative: boolean) { const name = typeof predicateOrNameOrKind === "string" ? predicateOrNameOrKind : undefined; const predicateOrKind = typeof predicateOrNameOrKind !== "string" ? predicateOrNameOrKind : undefined; const offset = this._currentEdge; const length = this._currentNode.edgeCount; for (let nextEdge = initializer(offset, length); bounded(nextEdge, length); nextEdge = seekDirection(nextEdge, length)) { if (!name || this._currentNode.edgeName(nextEdge) === name) { const next = this._currentNode.edgeValue(nextEdge); if (isNodeArray(next)) { const length = next.length; for (let nextOffset = initializer(0, length); bounded(nextOffset, length); nextOffset = seekDirection(nextOffset, length)) { const nextNode = next[nextOffset]; if (nextNode && matchPredicateOrKind(nextNode, predicateOrKind)) { if (!speculative) { this._beforeNavigate(); this._pushEdge(); this._setEdge(nextEdge, next, nextOffset, nextNode); this._afterNavigate(); } return true; } } } else if (next && matchPredicateOrKind(next, predicateOrKind)) { if (!speculative) { this._beforeNavigate(); this._pushEdge(); this._setEdge(nextEdge, /*array*/ undefined, /*offset*/ undefined, next); this._afterNavigate(); } return true; } } } return false; } private _moveToElement(currentArrayInitializer: SeekOperation, seekDirection: SeekOperation, currentEdge: number, currentArray: ReadonlyArray<Node> | undefined, currentOffset: number, predicateOrKind: SyntaxKind | ((node: Node) => boolean) | undefined, speculative: boolean) { if (!currentArray) { return false; } const offset = currentOffset; const length = currentArray.length; for (let nextOffset = currentArrayInitializer(offset, length); bounded(nextOffset, length); nextOffset = seekDirection(nextOffset, length)) { const nextNode = currentArray[nextOffset]; if (nextNode && matchPredicateOrKind(nextNode, predicateOrKind)) { if (!speculative) { this._beforeNavigate(); this._setEdge(currentEdge, currentArray, nextOffset, nextNode); this._afterNavigate(); } return true; } } return false; } private _moveToSibling(currentEdgeInitializer: SeekOperation, currentArrayInitializer: SeekOperation | undefined, nextArrayInitializer: SeekOperation, seekDirection: SeekOperation, parentNode: Node | undefined, predicateOrNameOrKind: string | SyntaxKind | ((node: Node) => boolean) | undefined, speculative: boolean) { if (!parentNode) { return false; } const name = typeof predicateOrNameOrKind === "string" ? predicateOrNameOrKind : undefined; const predicateOrKind = typeof predicateOrNameOrKind !== "string" ? predicateOrNameOrKind : undefined; if (currentArrayInitializer && this._moveToElement(currentArrayInitializer, seekDirection, this._currentEdge, this._currentArray, this._currentOffset, predicateOrKind, speculative)) { return true; } const offset = this._currentEdge; const length = parentNode.edgeCount; for (let nextEdge = currentEdgeInitializer(offset, length); bounded(nextEdge, length); nextEdge = seekDirection(nextEdge, length)) { if (!name || parentNode.edgeName(nextEdge) === name) { const next = parentNode.edgeValue(nextEdge); if (isNodeArray(next)) { if (this._moveToElement(nextArrayInitializer, seekDirection, nextEdge, next, 0, predicateOrKind, speculative)) { return true; } } else { if (next && matchPredicateOrKind(next, predicateOrKind)) { if (!speculative) { this._beforeNavigate(); this._setEdge(nextEdge, /*array*/ undefined, /*offset*/ undefined, next); this._afterNavigate(); } return true; } } } } return false; } private _reset() { this._currentDepth = 0; this._nodeStack.length = 1; this._edgeStack.length = 1; this._arrayStack.length = 1; this._offsetStack.length = 1; this._leadingTokens = undefined; this._trailingTokens = undefined; this._tokenOffset = -1; } } type SeekOperation = (offset: number, length: number) => number; namespace Navigation { export function first(offset: number, length: number) { return 0; } export function previous(offset: number, length: number) { return offset - 1; } export function same(offset: number, length: number) { return offset; } export function next(offset: number, length: number) { return offset + 1; } export function last(offset: number, length: number) { return length - 1; } } function bounded(offset: number, length: number) { return offset >= 0 && offset < length; } function matchProductionBody(node: Node) { return node.kind === SyntaxKind.OneOfList || node.kind === SyntaxKind.RightHandSideList || node.kind === SyntaxKind.RightHandSide; } function matchSourceElement(node: Node) { return node.kind === SyntaxKind.Import || node.kind === SyntaxKind.Production; } function isNodeArray(value: any): value is ReadonlyArray<Node> { return Array.isArray(value); } function matchPredicateOrKind(node: Node, predicateOrKind: SyntaxKind | ((node: Node) => boolean) | undefined): boolean { return typeof predicateOrKind === "function" ? predicateOrKind(node) : typeof predicateOrKind === "number" ? node.kind === predicateOrKind : true; } function getLeadingTokensMap(sourceFile: SourceFile) { let leadingTokensMap = perFileLeadingTokensMap.get(sourceFile); if (!leadingTokensMap) perFileLeadingTokensMap.set(sourceFile, leadingTokensMap = new Map()); return leadingTokensMap; } function getTrailingTokensMap(sourceFile: SourceFile) { let trailingTokensMap = perFileTrailingTokensMap.get(sourceFile); if (!trailingTokensMap) perFileTrailingTokensMap.set(sourceFile, trailingTokensMap = new Map()); return trailingTokensMap; } function getLeadingTokens(node: Node, sourceFile: SourceFile) { return perFileLeadingTokensMap.get(sourceFile)?.get(node); } function getTrailingTokens(node: Node, sourceFile: SourceFile) { return perFileTrailingTokensMap.get(sourceFile)?.get(node); } function scanInterveningTokens(parent: Node, sourceFile: SourceFile) { const trailingTokensMap = getTrailingTokensMap(sourceFile); if (trailingTokensMap.has(parent)) return; const leadingTokensMap = getLeadingTokensMap(sourceFile); const scanner = new Scanner(sourceFile.filename, sourceFile.text, NullDiagnosticMessages.instance); let pos = parent.pos; const processNode = (child: Node) => { const tokens = getTokens(pos, child.pos); leadingTokensMap.set(child, tokens); pos = child.end; }; const processNodes = (nodes: readonly Node[]) => { for (const child of nodes) { const tokens = getTokens(pos, child.pos); leadingTokensMap.set(child, tokens); pos = child.end; } }; const getTokens = (pos: number, end: number) => { let tokens: Token[] | null = null; scanner.scanRange(pos, () => { while (pos < end) { const token = scanner.scan(); if (token === SyntaxKind.EndOfFileToken) break; if (!isTokenKind(token)) throw new Error("Unexpected non-token in trivia"); const node = new Token(token); node.pos = pos; node.end = pos = scanner.getPos(); (tokens ??= []).push(node); } }); return tokens; }; for (let i = 0; i < parent.edgeCount; i++) { const edge = parent.edgeValue(i); if ((Array.isArray as (array: any) => array is readonly any[])(edge)) { processNodes(edge); } else if (edge) { processNode(edge); } } trailingTokensMap.set(parent, getTokens(pos, parent.end)); }
the_stack
import type { Fn2, ICopy, IEmpty, NumericArray } from "@thi.ng/api"; import { nomixin } from "@thi.ng/api/decorators/nomixin"; import { IGrid2DMixin } from "@thi.ng/api/mixins/igrid"; import { isNumber } from "@thi.ng/checks/is-number"; import { isString } from "@thi.ng/checks/is-string"; import { assert } from "@thi.ng/errors/assert"; import { clamp01 } from "@thi.ng/math/interval"; import type { BlendFnFloat, BlitOpts, Filter, FloatFormat, FloatFormatSpec, FloatSampler, IBlend, IBlit, IInvert, IntFormat, IPixelBuffer, IResizable, IToImageData, } from "./api.js"; import { ensureChannel, ensureSize } from "./checks.js"; import { defFloatFormat } from "./format/float-format.js"; import { FLOAT_GRAY } from "./format/float-gray.js"; import { FLOAT_RGBA } from "./index.js"; import { IntBuffer, intBufferFromCanvas, intBufferFromImage } from "./int.js"; import { __clampRegion, __prepRegions } from "./internal/utils.js"; import { defSampler } from "./sample.js"; /** * Syntax sugar for {@link FloatBuffer} ctor. * * @param w - * @param h - * @param fmt - * @param data - */ export function floatBuffer( w: number, h: number, fmt?: FloatFormat | FloatFormatSpec, data?: Float32Array ): FloatBuffer; export function floatBuffer( src: IntBuffer, fmt?: FloatFormat | FloatFormatSpec ): FloatBuffer; export function floatBuffer(...args: any[]) { return args[0] instanceof IntBuffer ? // @ts-ignore floatBufferFromInt(...args) : // @ts-ignore new FloatBuffer(...args); } /** * Creates a new `FloatBuffer` from given {@link IntBuffer} and using * provided {@link FloatFormat}. * * @remarks * See {@link FloatBuffer.as} for reverse operation. * * @param src * @param fmt */ export const floatBufferFromInt = ( src: IntBuffer, fmt?: FloatFormat | FloatFormatSpec ) => { const dest = new FloatBuffer(src.width, src.height, fmt); const { data: dbuf, format: dfmt, stride: [stride], } = dest; const { data: sbuf, format: sfmt } = src; for (let i = sbuf.length; i-- > 0; ) { dbuf.set(dfmt.fromABGR(sfmt.toABGR(sbuf[i])), i * stride); } return dest; }; export const floatBufferFromImage = ( img: HTMLImageElement, fmt?: FloatFormat | FloatFormatSpec, width?: number, height = width ) => floatBufferFromInt(intBufferFromImage(img, undefined, width, height), fmt); export const floatBufferFromCanvas = ( canvas: HTMLCanvasElement, fmt?: FloatFormat ) => floatBufferFromInt(intBufferFromCanvas(canvas), fmt); @IGrid2DMixin export class FloatBuffer implements IPixelBuffer<Float32Array, NumericArray>, IToImageData, IResizable<FloatBuffer, FloatSampler>, IBlend<FloatBuffer, BlendFnFloat>, IBlit<FloatBuffer>, IInvert<FloatBuffer>, ICopy<FloatBuffer>, IEmpty<FloatBuffer> { readonly size: [number, number]; readonly stride: [number, number]; readonly data: Float32Array; readonly format: FloatFormat; protected __empty: NumericArray; constructor( w: number, h: number, fmt: FloatFormat | FloatFormatSpec = FLOAT_RGBA, data?: Float32Array ) { this.size = [w, h]; this.format = (<any>fmt).__float ? <FloatFormat>fmt : defFloatFormat(fmt); // TODO support custom strides (via ctor arg) const stride = this.format.channels.length; this.stride = [stride, w * stride]; this.data = data || new Float32Array(w * h * stride); this.__empty = <NumericArray>( Object.freeze(new Array<number>(stride).fill(0)) ); } /** @deprecated use `.data` instead */ get pixels() { return this.data; } get width() { return this.size[0]; } get height() { return this.size[1]; } // TODO support custom offsets (via ctor arg) get offset() { return 0; } get dim(): 2 { return 2; } as(fmt: IntFormat) { const { width, height, stride: [stride], data, format: sfmt, } = this; const dest = new IntBuffer(width, height, fmt); const dpixels = dest.data; for (let i = 0, j = 0, n = data.length; i < n; i += stride, j++) { dpixels[j] = fmt.fromABGR( sfmt.toABGR(data.subarray(i, i + stride)) ); } return dest; } copy() { const dest = this.empty(); dest.data.set(this.data); return dest; } empty() { return new FloatBuffer(this.width, this.height, this.format); } // @ts-ignore mixin order(): number[] {} // @ts-ignore mixin includes(x: number, y: number): boolean {} // @ts-ignore mixin indexAt(x: number, y: number): number {} // @ts-ignore mixin indexAtUnsafe(x: number, y: number): number {} @nomixin getAt(x: number, y: number) { return this.includes(x, y) ? this.getAtUnsafe(x, y) : this.__empty; } @nomixin getAtUnsafe(x: number, y: number) { const idx = this.indexAtUnsafe(x, y); return this.data.subarray(idx, idx + this.stride[0]); } @nomixin setAt(x: number, y: number, col: NumericArray) { return this.includes(x, y) ? (this.data.set(col, this.indexAtUnsafe(x, y)), true) : false; } @nomixin setAtUnsafe(x: number, y: number, col: NumericArray) { this.data.set(col, this.indexAtUnsafe(x, y)); return true; } getChannelAt(x: number, y: number, id: number) { ensureChannel(this.format, id); return this.includes(x, y) ? this.data[this.indexAtUnsafe(x, y) + id] : undefined; } setChannelAt(x: number, y: number, id: number, col: number) { ensureChannel(this.format, id); this.includes(x, y) && (this.data[this.indexAtUnsafe(x, y) + id] = col); return this; } getChannel(id: number) { ensureChannel(this.format, id); const { data, stride: [stride], } = this; const dest = new Float32Array(this.width * this.height); for (let i = id, j = 0, n = data.length; i < n; i += stride, j++) { dest[j] = clamp01(data[i]); } return new FloatBuffer(this.width, this.height, FLOAT_GRAY, dest); } setChannel(id: number, src: FloatBuffer | number) { ensureChannel(this.format, id); const { data: dest, stride: [stride], } = this; if (isNumber(src)) { for (let i = id, n = dest.length; i < n; i += stride) { dest[i] = src; } } else { const { data: sbuf, stride: [sstride], } = src; ensureSize(sbuf, this.width, this.height, sstride); for ( let i = id, j = 0, n = dest.length; i < n; i += stride, j += sstride ) { dest[i] = sbuf[j]; } } return this; } blend(op: BlendFnFloat, dest: FloatBuffer, opts?: Partial<BlitOpts>) { this.ensureFormat(dest); const { sx, sy, dx, dy, rw, rh } = __prepRegions(this, dest, opts); if (rw < 1 || rh < 1) return dest; const sbuf = this.data; const dbuf = dest.data; const [stride, sw] = this.stride; const dw = dest.stride[1]; for ( let si = (sx | 0) * stride + (sy | 0) * sw, di = (dx | 0) * stride + (dy | 0) * dw, yy = 0; yy < rh; yy++, si += sw, di += dw ) { for ( let xx = rw, sii = si, dii = di; xx-- > 0; sii += stride, dii += stride ) { const out = dbuf.subarray(dii, dii + stride); op(out, sbuf.subarray(sii, sii + stride), out); } } return dest; } blit(dest: FloatBuffer, opts?: Partial<BlitOpts>) { this.ensureFormat(dest); const { sx, sy, dx, dy, rw, rh } = __prepRegions(this, dest, opts); if (rw < 1 || rh < 1) return dest; const sbuf = this.data; const dbuf = dest.data; const [stride, sw] = this.stride; const dw = dest.stride[1]; const rww = rw * stride; for ( let si = (sx | 0) * stride + (sy | 0) * sw, di = (dx | 0) * stride + (dy | 0) * dw, yy = 0; yy < rh; yy++, si += sw, di += dw ) { dbuf.set(sbuf.subarray(si, si + rww), di); } return dest; } blitCanvas( canvas: HTMLCanvasElement | CanvasRenderingContext2D, x = 0, y = 0 ) { const ctx = canvas instanceof HTMLCanvasElement ? canvas.getContext("2d")! : canvas; ctx.putImageData(this.toImageData(), x, y); } toImageData() { const idata = new ImageData(this.width, this.height); const dest = new Uint32Array(idata.data.buffer); const { stride: [stride], data, format, } = this; for (let i = 0, j = 0, n = data.length; i < n; i += stride, j++) { dest[j] = format.toABGR(data.subarray(i, i + stride)); } return idata; } getRegion(x: number, y: number, width: number, height: number) { const [sx, sy, w, h] = __clampRegion( x, y, width, height, this.width, this.height ); return this.blit(new FloatBuffer(w, h, this.format), { sx, sy, w, h, }); } forEach(f: Fn2<NumericArray, number, NumericArray>) { const { data, stride: [stride], } = this; for (let i = 0, j = 0, n = data.length; i < n; i += stride, j++) { data.set(f(data.subarray(i, i + stride), j), i); } return this; } clamp() { const data = this.data; for (let i = data.length; i-- > 0; ) { data[i] = clamp01(data[i]); } return this; } clampChannel(id: number) { ensureChannel(this.format, id); const { data, stride: [stride], } = this; for (let i = id, n = data.length; i < n; i += stride) { data[i] = clamp01(data[i]); } } /** * Flips image vertically. */ flipY() { const data = this.data; const rowStride = this.stride[1]; const tmp = new Float32Array(rowStride); for ( let i = 0, j = data.length - rowStride; i < j; i += rowStride, j -= rowStride ) { tmp.set(data.subarray(i, i + rowStride)); data.copyWithin(i, j, j + rowStride); data.set(tmp, j); } return this; } invert() { const { data, format, stride: [stride], } = this; for ( let i = 0, n = data.length, m = format.alpha ? stride - 1 : stride; i < n; i += stride ) { for (let j = 0; j < m; j++) data[i + j] = 1 - data[i + j]; } return this; } scale(scale: number, sampler?: FloatSampler | Filter) { assert(scale > 0, `scale must be > 0`); return this.resize(this.width * scale, this.height * scale, sampler); } resize(w: number, h: number, sampler: FloatSampler | Filter = "linear") { w |= 0; h |= 0; assert(w > 0 && h > 0, `target width & height must be > 0`); const dest = floatBuffer(w, h, this.format); const dpix = dest.data; const scaleX = w > 0 ? this.width / w : 0; const scaleY = h > 0 ? this.height / h : 0; const stride = this.stride[0]; sampler = isString(sampler) ? defSampler(this, sampler, "repeat") : sampler; for (let y = 0, i = 0; y < h; y++) { const yy = y * scaleY; for (let x = 0; x < w; x++, i += stride) { dpix.set(sampler(x * scaleX, yy), i); } } return dest; } upsize() { const { width, height, data, stride: [stride, rowStride], } = this; const stride2x = stride * 2; const dest = floatBuffer(width * 2, height * 2, this.format); const dpix = dest.data; for (let y = 0, si = 0; y < height; y++) { for ( let x = 0, di = y * rowStride * 4; x < width; x++, si += stride, di += stride2x ) { dpix.set(data.subarray(si, si + stride), di); } } return dest; } protected ensureFormat(dest: FloatBuffer) { assert( dest.format === this.format, `dest buffer format must be same as src` ); } }
the_stack
namespace gdjs { export type HotReloaderLog = { message: string; kind: 'fatal' | 'error' | 'warning' | 'info'; }; export type ChangedRuntimeBehavior = { oldBehaviorConstructor: Function; newBehaviorConstructor: Function; behaviorTypeName: string; }; /** * Reload scripts/data of an exported game and applies the changes * to the running runtime game. */ export class HotReloader { _runtimeGame: gdjs.RuntimeGame; _reloadedScriptElement: Record<string, HTMLScriptElement> = {}; _logs: HotReloaderLog[] = []; _alreadyLoadedScriptFiles: Record<string, boolean> = {}; /** * @param runtimeGame - The `gdjs.RuntimeGame` to be hot-reloaded. */ constructor(runtimeGame: gdjs.RuntimeGame) { this._runtimeGame = runtimeGame; } static groupByPersistentUuid< ObjectWithPersistentId extends { persistentUuid: string | null } >( objectsWithPersistentId: ObjectWithPersistentId[] ): Record<string, ObjectWithPersistentId> { return objectsWithPersistentId.reduce(function (objectsMap, object) { if (object.persistentUuid) { objectsMap[object.persistentUuid] = object; } return objectsMap; }, {}); } _canReloadScriptFile(srcFilename: string): boolean { function endsWith(str: string, suffix: string): boolean { const suffixPosition = str.indexOf(suffix); return ( suffixPosition !== -1 && suffixPosition === str.length - suffix.length ); } // Never reload .h script files, as they are leaking by mistake from C++ extensions. if (endsWith(srcFilename, '.h')) { return false; } // Make sure some files are loaded only once. if (this._alreadyLoadedScriptFiles[srcFilename]) { if ( // Don't reload Box2d as it would confuse and crash the asm.js library. endsWith(srcFilename, 'box2d.js') || // Don't reload shifty.js library. endsWith(srcFilename, 'shifty.js') || // Don't reload shopify-buy library. endsWith(srcFilename, 'shopify-buy.umd.polyfilled.min.js') || // Don't reload pixi-multistyle-text library. endsWith(srcFilename, 'pixi-multistyle-text.umd.js') || // Don't reload pixi-tilemap library. endsWith(srcFilename, 'pixi-tilemap.umd.js') || // Don't reload bondage.js library. endsWith(srcFilename, 'bondage.min.js') || // Don't reload pixi-particles library. endsWith(srcFilename, 'pixi-particles-pixi-renderer.min.js') || // Don't reload pixi-tilemap amd pixi-tilemap-helper libraries. endsWith(srcFilename, 'pixi-tilemap.umd.js') || endsWith(srcFilename, 'pixi-tilemap-helper.js') || // Don't reload pako library (used in pixi-tilemap) endsWith(srcFilename, 'pako/dist/pako.min') ) { return false; } } return true; } _reloadScript(srcFilename: string): Promise<void> { function endsWith(str: string, suffix: string): boolean { const suffixPosition = str.indexOf(suffix); return ( suffixPosition !== -1 && suffixPosition === str.length - suffix.length ); } if (!this._canReloadScriptFile(srcFilename)) { this._logs.push({ kind: 'info', message: 'Not reloading ' + srcFilename + ' as it is blocked for hot-reloading.', }); return Promise.resolve(); } const head = document.getElementsByTagName('head')[0]; if (!head) { return Promise.reject( new Error('No head element found, are you in a navigator?') ); } return new Promise((resolve, reject) => { const existingScriptElement = this._reloadedScriptElement[srcFilename]; if (existingScriptElement) { head.removeChild(existingScriptElement); } else { // Check if there is an existing scriptElement in head const headScriptElements = head.getElementsByTagName('script'); for (let i = 0; i < headScriptElements.length; ++i) { const scriptElement = headScriptElements[i]; if (endsWith(scriptElement.src, srcFilename)) { head.removeChild(scriptElement); } } } const reloadedScriptElement = document.createElement('script'); reloadedScriptElement.src = srcFilename + '?timestamp=' + Date.now(); reloadedScriptElement.onload = () => { resolve(); }; reloadedScriptElement.onerror = (event) => { reject(event); }; head.appendChild(reloadedScriptElement); this._reloadedScriptElement[srcFilename] = reloadedScriptElement; }); } hotReload(): Promise<HotReloaderLog[]> { console.info('Hot reload started'); this._runtimeGame.pause(true); this._logs = []; // Save old data of the project, to be used to compute // the difference between the old and new project data: const oldProjectData: ProjectData = gdjs.projectData; const oldScriptFiles = gdjs.runtimeGameOptions .scriptFiles as RuntimeGameOptionsScriptFile[]; oldScriptFiles.forEach((scriptFile) => { this._alreadyLoadedScriptFiles[scriptFile.path] = true; }); const oldBehaviorConstructors: { [key: string]: Function } = {}; for (let behaviorTypeName in gdjs.behaviorsTypes.items) { oldBehaviorConstructors[behaviorTypeName] = gdjs.behaviorsTypes.items[behaviorTypeName]; } // Reload projectData and runtimeGameOptions stored by convention in data.js: return this._reloadScript('data.js').then(() => { const newProjectData: ProjectData = gdjs.projectData; const newRuntimeGameOptions: RuntimeGameOptions = gdjs.runtimeGameOptions; const newScriptFiles = newRuntimeGameOptions.scriptFiles as RuntimeGameOptionsScriptFile[]; const projectDataOnlyExport = !!newRuntimeGameOptions.projectDataOnlyExport; // Reload the changed scripts, which will have the side effects of re-running // the new scripts, potentially replacing the code of the free functions from // extensions (which is fine) and registering updated behaviors (which will // need to be re-instantiated in runtime objects). return this.reloadScriptFiles( newProjectData, oldScriptFiles, newScriptFiles, projectDataOnlyExport ) .then(() => { const changedRuntimeBehaviors = this._computeChangedRuntimeBehaviors( oldBehaviorConstructors, gdjs.behaviorsTypes.items ); return this._hotReloadRuntimeGame( oldProjectData, newProjectData, changedRuntimeBehaviors, this._runtimeGame ); }) .catch((error) => { const errorTarget = error.target; if (errorTarget instanceof HTMLScriptElement) { this._logs.push({ kind: 'fatal', message: 'Unable to reload script:' + errorTarget.src, }); } else { this._logs.push({ kind: 'fatal', message: 'Unexpected error happened while hot-reloading:' + error.message, }); } }) .then(() => { console.info('Hot reload finished with logs:', this._logs); this._runtimeGame.pause(false); return this._logs; }); }); } _computeChangedRuntimeBehaviors( oldBehaviorConstructors: Record<string, Function>, newBehaviorConstructors: Record<string, Function> ): ChangedRuntimeBehavior[] { const changedRuntimeBehaviors: ChangedRuntimeBehavior[] = []; for (let behaviorTypeName in oldBehaviorConstructors) { const oldBehaviorConstructor = oldBehaviorConstructors[behaviorTypeName]; const newBehaviorConstructor = newBehaviorConstructors[behaviorTypeName]; if (!newBehaviorConstructor) { this._logs.push({ kind: 'warning', message: 'Behavior with type ' + behaviorTypeName + ' was removed from the registered behaviors in gdjs.', }); } else { if (oldBehaviorConstructor !== newBehaviorConstructor) { this._logs.push({ kind: 'info', message: 'Behavior with type ' + behaviorTypeName + ' was changed, and will be re-instantiated in gdjs.RuntimeObjects using it.', }); changedRuntimeBehaviors.push({ oldBehaviorConstructor, newBehaviorConstructor, behaviorTypeName, }); } } } return changedRuntimeBehaviors; } reloadScriptFiles( newProjectData: ProjectData, oldScriptFiles: RuntimeGameOptionsScriptFile[], newScriptFiles: RuntimeGameOptionsScriptFile[], projectDataOnlyExport: boolean ): Promise<void[]> { const reloadPromises: Array<Promise<void>> = []; // Reload events, only if they were exported. if (!projectDataOnlyExport) { newProjectData.layouts.forEach((_layoutData, index) => { reloadPromises.push(this._reloadScript('code' + index + '.js')); }); } for (let i = 0; i < newScriptFiles.length; ++i) { const newScriptFile = newScriptFiles[i]; const oldScriptFile = oldScriptFiles.filter( (scriptFile) => scriptFile.path === newScriptFile.path )[0]; if (!oldScriptFile) { // Script file added this._logs.push({ kind: 'info', message: 'Loading ' + newScriptFile.path + ' as it was added to the list of scripts.', }); reloadPromises.push(this._reloadScript(newScriptFile.path)); } else { // Script file changed, which can be the case for extensions created // from the editor, containing free functions or behaviors. if (newScriptFile.hash !== oldScriptFile.hash) { this._logs.push({ kind: 'info', message: 'Reloading ' + newScriptFile.path + ' because it was changed.', }); reloadPromises.push(this._reloadScript(newScriptFile.path)); } } } for (let i = 0; i < oldScriptFiles.length; ++i) { const oldScriptFile = oldScriptFiles[i]; const newScriptFile = newScriptFiles.filter( (scriptFile) => scriptFile.path === oldScriptFile.path )[0]; // A file may be removed because of a partial preview. if (!newScriptFile && !projectDataOnlyExport) { this._logs.push({ kind: 'warning', message: 'Script file ' + oldScriptFile.path + ' was removed.', }); } } return Promise.all(reloadPromises); } _hotReloadRuntimeGame( oldProjectData: ProjectData, newProjectData: ProjectData, changedRuntimeBehaviors: ChangedRuntimeBehavior[], runtimeGame: gdjs.RuntimeGame ): Promise<void> { return new Promise((resolve) => { // Update project data and re-load assets (sound/image/font/json managers // will take care of reloading only what is needed). runtimeGame.setProjectData(newProjectData); runtimeGame.loadAllAssets(() => { this._hotReloadVariablesContainer( oldProjectData.variables, newProjectData.variables, runtimeGame.getVariables() ); // Reload runtime scenes const sceneStack = runtimeGame.getSceneStack(); sceneStack._stack.forEach((runtimeScene) => { const oldLayoutData = oldProjectData.layouts.filter( (layoutData) => layoutData.name === runtimeScene.getName() )[0]; const newLayoutData = newProjectData.layouts.filter( (layoutData) => layoutData.name === runtimeScene.getName() )[0]; if (oldLayoutData && newLayoutData) { this._hotReloadRuntimeScene( oldLayoutData, newLayoutData, changedRuntimeBehaviors, runtimeScene ); } else { // A scene was removed. Not hot-reloading this. this._logs.push({ kind: 'error', message: 'Scene ' + oldLayoutData.name + ' was removed. A fresh preview should be launched.', }); } }); // Reload changes in external layouts newProjectData.externalLayouts.forEach((newExternalLayoutData) => { const oldExternalLayoutData = oldProjectData.externalLayouts.filter( (externalLayoutData) => externalLayoutData.name === newExternalLayoutData.name )[0]; if ( oldExternalLayoutData && // Check if there are actual changes, to avoid useless work trying to // hot-reload all the scenes. !HotReloader.deepEqual( oldExternalLayoutData, newExternalLayoutData ) ) { sceneStack._stack.forEach((runtimeScene) => { this._hotReloadRuntimeSceneInstances( oldExternalLayoutData.instances, newExternalLayoutData.instances, runtimeScene ); }); } }); resolve(); }); }); } _hotReloadVariablesContainer( oldVariablesData: RootVariableData[], newVariablesData: RootVariableData[], variablesContainer: gdjs.VariablesContainer ): void { newVariablesData.forEach((newVariableData) => { const variableName = newVariableData.name; const oldVariableData = oldVariablesData.find( (variable) => variable.name === variableName ); const variable = variablesContainer.get(newVariableData.name); if (!oldVariableData) { // New variable variablesContainer.add( variableName, new gdjs.Variable(newVariableData) ); } else if ( gdjs.Variable.isPrimitive(newVariableData.type || 'number') && (oldVariableData.value !== newVariableData.value || !gdjs.Variable.isPrimitive(oldVariableData.type || 'number')) ) { // Variable value was changed or was converted from // a structure to a variable with value. variablesContainer.remove(variableName); variablesContainer.add( variableName, new gdjs.Variable(newVariableData) ); } else if ( !gdjs.Variable.isPrimitive(newVariableData.type || 'number') ) { // Variable is a structure or array (or was converted from a primitive // to one of those). if (newVariableData.type === 'structure') this._hotReloadStructureVariable( //@ts-ignore If the type is structure, it is assured that the children have a name oldVariableData.children, newVariableData.children, variable ); else { // Arrays cannot be hot reloaded. // As indices can change at runtime, and in the IDE, they can be desychronized. // It will in that case mess up the whole array, // and there is no way to know if that was the case. // // We therefore just replace the old array with the new one. variablesContainer.remove(variableName); variablesContainer.add( variableName, new gdjs.Variable(newVariableData) ); } } }); oldVariablesData.forEach((oldVariableData) => { const newVariableData = newVariablesData.find( (variable) => variable.name === oldVariableData.name ); if (!newVariableData) { // Variable was removed variablesContainer.remove(oldVariableData.name); } }); } _hotReloadStructureVariable( oldChildren: RootVariableData[], newChildren: RootVariableData[], variable: gdjs.Variable ): void { if (oldChildren) { oldChildren.forEach((oldChildVariableData) => { const newChildVariableData = newChildren.find( (childVariableData) => childVariableData.name === oldChildVariableData.name ); if (!newChildVariableData) { // Child variable was removed. variable.removeChild(oldChildVariableData.name); } else if ( gdjs.Variable.isPrimitive(newChildVariableData.type || 'number') && (oldChildVariableData.value !== newChildVariableData.value || !gdjs.Variable.isPrimitive(oldChildVariableData.type || 'number')) ) { // The child variable value was changed or was converted from // structure to a variable with value. variable.addChild( newChildVariableData.name, new gdjs.Variable(newChildVariableData) ); } else if ( !gdjs.Variable.isPrimitive(newChildVariableData.type || 'number') ) { // Variable is a structure or array (or was converted from a primitive // to one of those). if (newChildVariableData.type === 'structure') this._hotReloadStructureVariable( //@ts-ignore If the type is structure, it is assured that the children have a name oldChildVariableData.children, newChildVariableData.children as Required<VariableData>[], variable.getChild(newChildVariableData.name) ); else { // Arrays cannot be hot reloaded. // As indices can change at runtime, and in the IDE, they can be desychronized. // It will in that case mess up the whole array, // and there is no way to know if that was the case. // // We therefore just replace the old array with the new one. variable.addChild( newChildVariableData.name, new gdjs.Variable(newChildVariableData) ); } } }); newChildren.forEach((newChildVariableData) => { const oldChildVariableData = oldChildren.find( (childVariableData) => childVariableData.name === newChildVariableData.name ); if (!oldChildVariableData) { // Child variable was added variable.addChild( newChildVariableData.name, new gdjs.Variable(newChildVariableData) ); } }); } else { // Variable was converted from a value to a structure: newChildren.forEach((newChildVariableData) => { variable.addChild( newChildVariableData.name, new gdjs.Variable(newChildVariableData) ); }); } } _hotReloadRuntimeScene( oldLayoutData: LayoutData, newLayoutData: LayoutData, changedRuntimeBehaviors: ChangedRuntimeBehavior[], runtimeScene: gdjs.RuntimeScene ): void { runtimeScene.setBackgroundColor( newLayoutData.r, newLayoutData.v, newLayoutData.b ); if (oldLayoutData.title !== newLayoutData.title) { runtimeScene .getGame() .getRenderer() .setWindowTitle(newLayoutData.title); } this._hotReloadVariablesContainer( oldLayoutData.variables as Required<VariableData>[], newLayoutData.variables as Required<VariableData>[], runtimeScene.getVariables() ); this._hotReloadRuntimeSceneBehaviorsSharedData( oldLayoutData.behaviorsSharedData, newLayoutData.behaviorsSharedData, runtimeScene ); // Re-instantiate any gdjs.RuntimeBehavior that was changed. this._reinstantiateRuntimeSceneRuntimeBehaviors( changedRuntimeBehaviors, newLayoutData.objects, runtimeScene ); this._hotReloadRuntimeSceneObjects( oldLayoutData.objects, newLayoutData.objects, runtimeScene ); this._hotReloadRuntimeSceneInstances( oldLayoutData.instances, newLayoutData.instances, runtimeScene ); this._hotReloadRuntimeSceneLayers( oldLayoutData.layers, newLayoutData.layers, runtimeScene ); // Update the events generated code launched at each frame. Events generated code // script files were already reloaded at the beginning of the hot-reload. Note that // if they have not changed, it's still fine to call this, it will be basically a // no-op. runtimeScene.setEventsGeneratedCodeFunction(newLayoutData); } _hotReloadRuntimeSceneBehaviorsSharedData( oldBehaviorsSharedData: BehaviorSharedData[], newBehaviorsSharedData: BehaviorSharedData[], runtimeScene: gdjs.RuntimeScene ): void { oldBehaviorsSharedData.forEach((oldBehaviorSharedData) => { const name = oldBehaviorSharedData.name; const newBehaviorSharedData = newBehaviorsSharedData.filter( (behaviorSharedData) => behaviorSharedData.name === name )[0]; if (!newBehaviorSharedData) { // Behavior shared data was removed. runtimeScene.setInitialSharedDataForBehavior( oldBehaviorSharedData.name, null ); } else { if ( !HotReloader.deepEqual(oldBehaviorSharedData, newBehaviorSharedData) ) { // Behavior shared data was modified runtimeScene.setInitialSharedDataForBehavior( newBehaviorSharedData.name, newBehaviorSharedData ); } } }); newBehaviorsSharedData.forEach((newBehaviorSharedData) => { const name = newBehaviorSharedData.name; const oldBehaviorSharedData = oldBehaviorsSharedData.filter( (behaviorSharedData) => behaviorSharedData.name === name )[0]; if (!oldBehaviorSharedData) { // Behavior shared data was added runtimeScene.setInitialSharedDataForBehavior( newBehaviorSharedData.name, newBehaviorSharedData ); } }); } _reinstantiateRuntimeSceneRuntimeBehaviors( changedRuntimeBehaviors: ChangedRuntimeBehavior[], newObjects: ObjectData[], runtimeScene: gdjs.RuntimeScene ): void { newObjects.forEach((newObjectData) => { const objectName = newObjectData.name; const newBehaviors = newObjectData.behaviors; const runtimeObjects = runtimeScene.getObjects(objectName); changedRuntimeBehaviors.forEach((changedRuntimeBehavior) => { const behaviorTypeName = changedRuntimeBehavior.behaviorTypeName; // If the changed behavior is used by the object, re-instantiate // it. newBehaviors .filter((behaviorData) => behaviorData.type === behaviorTypeName) .forEach((changedBehaviorNewData) => { const name = changedBehaviorNewData.name; this._logs.push({ kind: 'info', message: 'Re-instantiating behavior named "' + name + '" for instances of object "' + objectName + '".', }); runtimeObjects.forEach((runtimeObject) => { this._reinstantiateRuntimeObjectRuntimeBehavior( changedBehaviorNewData, runtimeObject ); }); }); }); }); } _reinstantiateRuntimeObjectRuntimeBehavior( behaviorData: BehaviorData, runtimeObject: gdjs.RuntimeObject ): void { const behaviorName = behaviorData.name; const oldRuntimeBehavior = runtimeObject.getBehavior(behaviorName); if (!oldRuntimeBehavior) { return; } // Remove and re-add the behavior so that it's using the newly // registered gdjs.RuntimeBehavior. runtimeObject.removeBehavior(behaviorName); runtimeObject.addNewBehavior(behaviorData); const newRuntimeBehavior = runtimeObject.getBehavior(behaviorName); if (!newRuntimeBehavior) { this._logs.push({ kind: 'error', message: 'Could not create behavior ' + behaviorName + ' (type: ' + behaviorData.type + ') for object ' + runtimeObject.getName(), }); return; } // Copy the properties from the old behavior to the new one. for (let behaviorProperty in oldRuntimeBehavior) { if (!oldRuntimeBehavior.hasOwnProperty(behaviorProperty)) { continue; } if (behaviorProperty === '_behaviorData') { // For property "_behaviorData" that we know to be an object, // do a copy of each property of // this object so that we keep the new ones (useful if a new property was added). newRuntimeBehavior[behaviorProperty] = newRuntimeBehavior[behaviorProperty] || {}; for (let property in oldRuntimeBehavior[behaviorProperty]) { newRuntimeBehavior[behaviorProperty][property] = oldRuntimeBehavior[behaviorProperty][property]; } } else { newRuntimeBehavior[behaviorProperty] = oldRuntimeBehavior[behaviorProperty]; } } return; } _hotReloadRuntimeSceneObjects( oldObjects: ObjectData[], newObjects: ObjectData[], runtimeScene: gdjs.RuntimeScene ): void { oldObjects.forEach((oldObjectData) => { const name = oldObjectData.name; const newObjectData = newObjects.filter( (objectData) => objectData.name === name )[0]; // Note: if an object is renamed in the editor, it will be considered as removed, // and the new object name as a new object to register. // It's not ideal because living instances of the object will be destroyed, // but it would be complex to iterate over instances of the object and change // its name (it's not expected to change). if (!newObjectData || oldObjectData.type !== newObjectData.type) { // Object was removed or object type was changed (considered as a removal of the old object) runtimeScene.unregisterObject(name); } else { if (runtimeScene.isObjectRegistered(name)) { this._hotReloadRuntimeSceneObject( oldObjectData, newObjectData, runtimeScene ); } } }); newObjects.forEach((newObjectData) => { const name = newObjectData.name; const oldObjectData = oldObjects.filter( (layerData) => layerData.name === name )[0]; if ( (!oldObjectData || oldObjectData.type !== newObjectData.type) && !runtimeScene.isObjectRegistered(name) ) { // Object was added or object type was changed (considered as adding the new object) runtimeScene.registerObject(newObjectData); } }); } _hotReloadRuntimeSceneObject( oldObjectData: ObjectData, newObjectData: ObjectData, runtimeScene: gdjs.RuntimeScene ): void { let hotReloadSucceeded = true; if (!HotReloader.deepEqual(oldObjectData, newObjectData)) { this._logs.push({ kind: 'info', message: 'Object "' + newObjectData.name + '" was modified and is hot-reloaded.', }); // Register the updated object data, used for new instances. runtimeScene.updateObject(newObjectData); // Update existing instances const runtimeObjects = runtimeScene.getObjects(newObjectData.name); // Update instances state runtimeObjects.forEach((runtimeObject) => { // Update the runtime object hotReloadSucceeded = runtimeObject.updateFromObjectData(oldObjectData, newObjectData) && hotReloadSucceeded; }); // Don't update the variables, behaviors and effects for each runtime object to avoid // doing the check for differences for every single object. // Update variables runtimeObjects.forEach((runtimeObject) => { this._hotReloadVariablesContainer( oldObjectData.variables as Required<VariableData>[], newObjectData.variables as Required<VariableData>[], runtimeObject.getVariables() ); }); // Update behaviors this._hotReloadRuntimeObjectsBehaviors( oldObjectData.behaviors, newObjectData.behaviors, runtimeObjects ); // Update effects this._hotReloadRuntimeObjectsEffects( oldObjectData.effects, newObjectData.effects, runtimeObjects ); } if (!hotReloadSucceeded) { this._logs.push({ kind: 'error', message: 'Object "' + newObjectData.name + '" could not be hot-reloaded. A fresh preview should be run.', }); } } _hotReloadRuntimeObjectsBehaviors( oldBehaviors: BehaviorData[], newBehaviors: BehaviorData[], runtimeObjects: gdjs.RuntimeObject[] ): void { oldBehaviors.forEach((oldBehaviorData) => { const name = oldBehaviorData.name; const newBehaviorData = newBehaviors.filter( (behaviorData) => behaviorData.name === name )[0]; if (!newBehaviorData) { // Behavior was removed runtimeObjects.forEach((runtimeObject) => { if (runtimeObject.hasBehavior(name)) { if (!runtimeObject.removeBehavior(name)) { this._logs.push({ kind: 'error', message: 'Behavior ' + name + ' could not be removed from object' + runtimeObject.getName(), }); } } }); } else { if (!HotReloader.deepEqual(oldBehaviorData, newBehaviorData)) { let hotReloadSucceeded = true; runtimeObjects.forEach((runtimeObject) => { const runtimeBehavior = runtimeObject.getBehavior( newBehaviorData.name ); if (runtimeBehavior) { hotReloadSucceeded = this._hotReloadRuntimeBehavior( oldBehaviorData, newBehaviorData, runtimeBehavior ) && hotReloadSucceeded; } }); if (!hotReloadSucceeded) { this._logs.push({ kind: 'error', message: newBehaviorData.name + ' behavior could not be hot-reloaded.', }); } } } }); newBehaviors.forEach((newBehaviorData) => { const name = newBehaviorData.name; const oldBehaviorData = oldBehaviors.filter( (layerData) => layerData.name === name )[0]; if (!oldBehaviorData) { // Behavior was added let hotReloadSucceeded = true; runtimeObjects.forEach((runtimeObject) => { hotReloadSucceeded = runtimeObject.addNewBehavior(newBehaviorData) && hotReloadSucceeded; }); if (!hotReloadSucceeded) { this._logs.push({ kind: 'error', message: newBehaviorData.name + ' behavior could not be added during hot-reload.', }); } } }); } _hotReloadRuntimeObjectsEffects( oldEffects: EffectData[], newEffects: EffectData[], runtimeObjects: RuntimeObject[] ): void { oldEffects.forEach((oldEffectData) => { const name = oldEffectData.name; const newEffectData = newEffects.filter( (effectData) => effectData.name === name )[0]; if (!newEffectData) { // Effect was removed. runtimeObjects.forEach((runtimeObject) => { if (runtimeObject.hasEffect(name)) { if (!runtimeObject.removeEffect(name)) { this._logs.push({ kind: 'error', message: 'Effect ' + name + ' could not be removed from object' + runtimeObject.getName(), }); } } }); } else { if (!HotReloader.deepEqual(oldEffectData, newEffectData)) { let hotReloadSucceeded = true; runtimeObjects.forEach((runtimeObject) => { if (oldEffectData.effectType === newEffectData.effectType) { hotReloadSucceeded = runtimeObject.updateAllEffectParameters(newEffectData) && hotReloadSucceeded; } else { // Another effect type was applied runtimeObject.removeEffect(oldEffectData.name); runtimeObject.addEffect(newEffectData); } }); if (!hotReloadSucceeded) { this._logs.push({ kind: 'error', message: newEffectData.name + ' effect could not be hot-reloaded.', }); } } } }); newEffects.forEach((newEffectData) => { const name = newEffectData.name; const oldEffectData = oldEffects.filter( (oldEffectData) => oldEffectData.name === name )[0]; if (!oldEffectData) { // Effect was added let hotReloadSucceeded = true; runtimeObjects.forEach((runtimeObject) => { hotReloadSucceeded = runtimeObject.addEffect(newEffectData) && hotReloadSucceeded; }); if (!hotReloadSucceeded) { this._logs.push({ kind: 'error', message: newEffectData.name + ' effect could not be added during hot-reload.', }); } } }); } /** * @returns true if hot-reload succeeded, false otherwise. */ _hotReloadRuntimeBehavior( oldBehaviorData: BehaviorData, newBehaviorData: BehaviorData, runtimeBehavior: gdjs.RuntimeBehavior ): boolean { // Don't check here for deep equality between oldBehaviorData and newBehaviorData. // This would be too costly to do for each runtime object. // It's supposed to be done once by the caller. return runtimeBehavior.updateFromBehaviorData( oldBehaviorData, newBehaviorData ); } _hotReloadRuntimeSceneLayers( oldLayers: LayerData[], newLayers: LayerData[], runtimeScene: gdjs.RuntimeScene ): void { oldLayers.forEach((oldLayerData) => { const name = oldLayerData.name; const newLayerData = newLayers.filter( (layerData) => layerData.name === name )[0]; if (!newLayerData) { // Layer was removed runtimeScene.removeLayer(name); } else { if (runtimeScene.hasLayer(name)) { const layer = runtimeScene.getLayer(name); this._hotReloadRuntimeLayer(oldLayerData, newLayerData, layer); } } }); newLayers.forEach((newLayerData) => { const name = newLayerData.name; const oldLayerData = oldLayers.filter( (layerData) => layerData.name === name )[0]; if (!oldLayerData && !runtimeScene.hasLayer(name)) { // Layer was added runtimeScene.addLayer(newLayerData); } }); newLayers.forEach((newLayerData, index) => { runtimeScene.setLayerIndex(newLayerData.name, index); }); } _hotReloadRuntimeLayer( oldLayer: LayerData, newLayer: LayerData, runtimeLayer: gdjs.Layer ): void { // Properties if (oldLayer.visibility !== newLayer.visibility) { runtimeLayer.show(newLayer.visibility); } if (newLayer.isLightingLayer) { if ( oldLayer.ambientLightColorR !== newLayer.ambientLightColorR || oldLayer.ambientLightColorG !== newLayer.ambientLightColorG || oldLayer.ambientLightColorB !== newLayer.ambientLightColorB ) { runtimeLayer.setClearColor( newLayer.ambientLightColorR, newLayer.ambientLightColorG, newLayer.ambientLightColorB ); } if (oldLayer.followBaseLayerCamera !== newLayer.followBaseLayerCamera) { runtimeLayer.setFollowBaseLayerCamera(newLayer.followBaseLayerCamera); } } // TODO: cameras // Effects this._hotReloadRuntimeLayerEffects( oldLayer.effects, newLayer.effects, runtimeLayer ); } _hotReloadRuntimeLayerEffects( oldEffectsData: EffectData[], newEffectsData: EffectData[], runtimeLayer: gdjs.Layer ): void { oldEffectsData.forEach((oldEffectData) => { const name = oldEffectData.name; const newEffectData = newEffectsData.filter( (effectData) => effectData.name === name )[0]; if (!newEffectData) { // Effect was removed runtimeLayer.removeEffect(name); } else { if (runtimeLayer.hasEffect(name)) { if (oldEffectData.effectType !== newEffectData.effectType) { // Effect changed type, consider it was removed and added back. runtimeLayer.removeEffect(name); runtimeLayer.addEffect(newEffectData); } else { this._hotReloadRuntimeLayerEffect( oldEffectData, newEffectData, runtimeLayer, name ); } } } }); newEffectsData.forEach((newEffectData) => { const name = newEffectData.name; const oldEffectData = oldEffectsData.filter( (layerData) => layerData.name === name )[0]; if (!oldEffectData && !runtimeLayer.hasEffect(name)) { // Effect was added runtimeLayer.addEffect(newEffectData); } }); } _hotReloadRuntimeLayerEffect( oldEffectData: EffectData, newEffectData: EffectData, runtimeLayer: gdjs.Layer, effectName: string ): void { // We consider oldEffectData.effectType and newEffectData.effectType // are the same - it's responsibility of the caller to verify this. for (let parameterName in newEffectData.booleanParameters) { const value = newEffectData.booleanParameters[parameterName]; if (value !== oldEffectData.booleanParameters[parameterName]) { runtimeLayer.setEffectBooleanParameter( effectName, parameterName, value ); } } for (let parameterName in newEffectData.doubleParameters) { const value = newEffectData.doubleParameters[parameterName]; if (value !== oldEffectData.doubleParameters[parameterName]) { runtimeLayer.setEffectDoubleParameter( effectName, parameterName, value ); } } for (let parameterName in newEffectData.stringParameters) { const value = newEffectData.stringParameters[parameterName]; if (value !== oldEffectData.stringParameters[parameterName]) { runtimeLayer.setEffectStringParameter( effectName, parameterName, value ); } } } _hotReloadRuntimeSceneInstances( oldInstances: InstanceData[], newInstances: InstanceData[], runtimeScene: gdjs.RuntimeScene ): void { const runtimeObjects = runtimeScene.getAdhocListOfAllInstances(); const groupedOldInstances: { [key: number]: InstanceData; } = HotReloader.groupByPersistentUuid(oldInstances); const groupedNewInstances: { [key: number]: InstanceData; } = HotReloader.groupByPersistentUuid(newInstances); const groupedRuntimeObjects: { [key: number]: gdjs.RuntimeObject; } = HotReloader.groupByPersistentUuid(runtimeObjects); for (let persistentUuid in groupedOldInstances) { const oldInstance = groupedOldInstances[persistentUuid]; const newInstance = groupedNewInstances[persistentUuid]; const runtimeObject = groupedRuntimeObjects[persistentUuid]; if ( oldInstance && (!newInstance || oldInstance.name !== newInstance.name) ) { // Instance was deleted (or object name changed, in which case it will be re-created later) if (runtimeObject) { runtimeObject.deleteFromScene(runtimeScene); } } else { if (oldInstance && newInstance && runtimeObject) { // Instance was not deleted nor created, maybe modified (or not): this._hotReloadRuntimeInstance( oldInstance, newInstance, runtimeObject ); } } } for (let persistentUuid in groupedNewInstances) { const oldInstance = groupedOldInstances[persistentUuid]; const newInstance = groupedNewInstances[persistentUuid]; const runtimeObject = groupedRuntimeObjects[persistentUuid]; if ( newInstance && (!oldInstance || oldInstance.name !== newInstance.name) && !runtimeObject ) { // Instance was created (or object name changed, in which case it was destroyed previously) // and we verified that runtimeObject does not exist. runtimeScene.createObjectsFrom( [newInstance], 0, 0, /*trackByPersistentUuid=*/ true ); } } } _hotReloadRuntimeInstance( oldInstance: InstanceData, newInstance: InstanceData, runtimeObject: gdjs.RuntimeObject ): void { let somethingChanged = false; // Check if default properties changed if (oldInstance.x !== newInstance.x) { runtimeObject.setX(newInstance.x); somethingChanged = true; } if (oldInstance.y !== newInstance.y) { runtimeObject.setY(newInstance.y); somethingChanged = true; } if (oldInstance.angle !== newInstance.angle) { runtimeObject.setAngle(newInstance.angle); somethingChanged = true; } if (oldInstance.zOrder !== newInstance.zOrder) { runtimeObject.setZOrder(newInstance.zOrder); somethingChanged = true; } if (oldInstance.layer !== newInstance.layer) { runtimeObject.setLayer(newInstance.layer); somethingChanged = true; } // Check if size changed let sizeChanged = false; if (newInstance.customSize) { if (!oldInstance.customSize) { // A custom size was set runtimeObject.setWidth(newInstance.width); runtimeObject.setHeight(newInstance.height); somethingChanged = true; sizeChanged = true; } else { // The custom size was changed if (oldInstance.width !== newInstance.width) { runtimeObject.setWidth(newInstance.width); somethingChanged = true; sizeChanged = true; } if (oldInstance.height !== newInstance.height) { runtimeObject.setHeight(newInstance.height); somethingChanged = true; sizeChanged = true; } } } else { if (!newInstance.customSize && oldInstance.customSize) { // The custom size was removed. Just flag the size as changed // and hope the object will handle this in // `extraInitializationFromInitialInstance`. sizeChanged = true; } } // Update variables this._hotReloadVariablesContainer( oldInstance.initialVariables as Required<VariableData>[], newInstance.initialVariables as Required<VariableData>[], runtimeObject.getVariables() ); // Check if custom properties changed (specific to each object type) const numberPropertiesChanged = newInstance.numberProperties.some( (numberProperty) => { const name = numberProperty.name; const value = numberProperty.value; const oldNumberProperty = oldInstance.numberProperties.filter( (numberProperty) => numberProperty.name === name )[0]; return !oldNumberProperty || oldNumberProperty.value !== value; } ); const stringPropertiesChanged = newInstance.stringProperties.some( (stringProperty) => { const name = stringProperty.name; const value = stringProperty.value; const oldStringProperty = oldInstance.stringProperties.filter( (stringProperty) => stringProperty.name === name )[0]; return !oldStringProperty || oldStringProperty.value !== value; } ); if (numberPropertiesChanged || stringPropertiesChanged || sizeChanged) { runtimeObject.extraInitializationFromInitialInstance(newInstance); somethingChanged = true; } if (somethingChanged) { // If we changed the runtime object position/size/angle or another property, // notify behaviors that the runtime object was reloaded. // This is useful for behaviors like the physics engine that are watching the // object position/size and need to be notified when changed (otherwise, they // would continue using the previous position, so the object would not be moved // or updated according to the changes made in the project instance). runtimeObject.notifyBehaviorsObjectHotReloaded(); } } /** * Deep check equality between the two objects/arrays/primitives. * * Inspired from https://github.com/epoberezkin/fast-deep-equal * @param a The first object/array/primitive to compare * @param b The second object/array/primitive to compare */ static deepEqual(a: any, b: any): boolean { if (a === b) { return true; } if (a && b && typeof a == 'object' && typeof b == 'object') { if (a.constructor !== b.constructor) { return false; } let length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) { return false; } for (i = length; i-- !== 0; ) { if (!HotReloader.deepEqual(a[i], b[i])) { return false; } } return true; } if (a.valueOf !== Object.prototype.valueOf) { return a.valueOf() === b.valueOf(); } if (a.toString !== Object.prototype.toString) { return a.toString() === b.toString(); } keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) { return false; } for (i = length; i-- !== 0; ) { if (!Object.prototype.hasOwnProperty.call(b, keys[i])) { return false; } } for (i = length; i-- !== 0; ) { const key = keys[i]; if (!HotReloader.deepEqual(a[key], b[key])) { return false; } } return true; } // true if both NaN, false otherwise return a !== a && b !== b; } } }
the_stack
import { IFunctionIdentifier, ITerminalOptions as IPublicTerminalOptions } from 'xterm'; import { IEvent, IEventEmitter } from 'common/EventEmitter'; import { IDeleteEvent, IInsertEvent } from 'common/CircularList'; import { IParams } from 'common/parser/Types'; import { IOptionsService, IUnicodeService } from 'common/services/Services'; export interface ICoreTerminal { optionsService: IOptionsService; unicodeService: IUnicodeService; } export interface IDisposable { dispose(): void; } // TODO: The options that are not in the public API should be reviewed export interface ITerminalOptions extends IPublicTerminalOptions { [key: string]: any; cancelEvents?: boolean; convertEol?: boolean; termName?: string; } export type XtermListener = (...args: any[]) => void; /** * A keyboard event interface which does not depend on the DOM, KeyboardEvent implicitly extends * this event. */ export interface IKeyboardEvent { altKey: boolean; ctrlKey: boolean; shiftKey: boolean; metaKey: boolean; keyCode: number; key: string; type: string; } export interface IScrollEvent { position: number; source: ScrollSource; } export const enum ScrollSource { TERMINAL, VIEWPORT, } export interface ICircularList<T> { length: number; maxLength: number; isFull: boolean; onDeleteEmitter: IEventEmitter<IDeleteEvent>; onDelete: IEvent<IDeleteEvent>; onInsertEmitter: IEventEmitter<IInsertEvent>; onInsert: IEvent<IInsertEvent>; onTrimEmitter: IEventEmitter<number>; onTrim: IEvent<number>; get(index: number): T | undefined; set(index: number, value: T): void; push(value: T): void; recycle(): T; pop(): T | undefined; splice(start: number, deleteCount: number, ...items: T[]): void; trimStart(count: number): void; shiftElements(start: number, count: number, offset: number): void; } export const enum KeyboardResultType { SEND_KEY, SELECT_ALL, PAGE_UP, PAGE_DOWN } export interface IKeyboardResult { type: KeyboardResultType; cancel: boolean; key: string | undefined; } export interface ICharset { [key: string]: string | undefined; } export type CharData = [number, string, number, number]; export type IColorRGB = [number, number, number]; export interface IExtendedAttrs { underlineStyle: number; underlineColor: number; clone(): IExtendedAttrs; isEmpty(): boolean; } /** Attribute data */ export interface IAttributeData { fg: number; bg: number; extended: IExtendedAttrs; clone(): IAttributeData; // flags isInverse(): number; isBold(): number; isUnderline(): number; isBlink(): number; isInvisible(): number; isItalic(): number; isDim(): number; // color modes getFgColorMode(): number; getBgColorMode(): number; isFgRGB(): boolean; isBgRGB(): boolean; isFgPalette(): boolean; isBgPalette(): boolean; isFgDefault(): boolean; isBgDefault(): boolean; isAttributeDefault(): boolean; // colors getFgColor(): number; getBgColor(): number; // extended attrs hasExtendedAttrs(): number; updateExtended(): void; getUnderlineColor(): number; getUnderlineColorMode(): number; isUnderlineColorRGB(): boolean; isUnderlineColorPalette(): boolean; isUnderlineColorDefault(): boolean; getUnderlineStyle(): number; } /** Cell data */ export interface ICellData extends IAttributeData { content: number; combinedData: string; isCombined(): number; getWidth(): number; getChars(): string; getCode(): number; setFromCharData(value: CharData): void; getAsCharData(): CharData; } /** * Interface for a line in the terminal buffer. */ export interface IBufferLine { length: number; isWrapped: boolean; get(index: number): CharData; set(index: number, value: CharData): void; loadCell(index: number, cell: ICellData): ICellData; setCell(index: number, cell: ICellData): void; setCellFromCodePoint(index: number, codePoint: number, width: number, fg: number, bg: number, eAttrs: IExtendedAttrs): void; addCodepointToCell(index: number, codePoint: number): void; insertCells(pos: number, n: number, ch: ICellData, eraseAttr?: IAttributeData): void; deleteCells(pos: number, n: number, fill: ICellData, eraseAttr?: IAttributeData): void; replaceCells(start: number, end: number, fill: ICellData, eraseAttr?: IAttributeData): void; resize(cols: number, fill: ICellData): void; fill(fillCellData: ICellData): void; copyFrom(line: IBufferLine): void; clone(): IBufferLine; getTrimmedLength(): number; translateToString(trimRight?: boolean, startCol?: number, endCol?: number): string; /* direct access to cell attrs */ getWidth(index: number): number; hasWidth(index: number): number; getFg(index: number): number; getBg(index: number): number; hasContent(index: number): number; getCodePoint(index: number): number; isCombined(index: number): number; getString(index: number): string; } export interface IMarker extends IDisposable { readonly id: number; readonly isDisposed: boolean; readonly line: number; onDispose: IEvent<void>; } export interface IModes { insertMode: boolean; } export interface IDecPrivateModes { applicationCursorKeys: boolean; applicationKeypad: boolean; bracketedPasteMode: boolean; origin: boolean; reverseWraparound: boolean; sendFocus: boolean; wraparound: boolean; // defaults: xterm - true, vt100 - false } export interface IRowRange { start: number; end: number; } /** * Interface for mouse events in the core. */ export const enum CoreMouseButton { LEFT = 0, MIDDLE = 1, RIGHT = 2, NONE = 3, WHEEL = 4, // additional buttons 1..8 // untested! AUX1 = 8, AUX2 = 9, AUX3 = 10, AUX4 = 11, AUX5 = 12, AUX6 = 13, AUX7 = 14, AUX8 = 15 } export const enum CoreMouseAction { UP = 0, // buttons, wheel DOWN = 1, // buttons, wheel LEFT = 2, // wheel only RIGHT = 3, // wheel only MOVE = 32 // buttons only } export interface ICoreMouseEvent { /** column (zero based). */ col: number; /** row (zero based). */ row: number; /** * Button the action occured. Due to restrictions of the tracking protocols * it is not possible to report multiple buttons at once. * Wheel is treated as a button. * There are invalid combinations of buttons and actions possible * (like move + wheel), those are silently ignored by the CoreMouseService. */ button: CoreMouseButton; action: CoreMouseAction; /** * Modifier states. * Protocols will add/ignore those based on specific restrictions. */ ctrl?: boolean; alt?: boolean; shift?: boolean; } /** * CoreMouseEventType * To be reported to the browser component which events a mouse * protocol wants to be catched and forwarded as an ICoreMouseEvent * to CoreMouseService. */ export const enum CoreMouseEventType { NONE = 0, /** any mousedown event */ DOWN = 1, /** any mouseup event */ UP = 2, /** any mousemove event while a button is held */ DRAG = 4, /** any mousemove event without a button */ MOVE = 8, /** any wheel event */ WHEEL = 16 } /** * Mouse protocol interface. * A mouse protocol can be registered and activated at the CoreMouseService. * `events` should contain a list of needed events as a hint for the browser component * to install/remove the appropriate event handlers. * `restrict` applies further protocol specific restrictions like not allowed * modifiers or filtering invalid event types. */ export interface ICoreMouseProtocol { events: CoreMouseEventType; restrict: (e: ICoreMouseEvent) => boolean; } /** * CoreMouseEncoding * The tracking encoding can be registered and activated at the CoreMouseService. * If a ICoreMouseEvent passes all procotol restrictions it will be encoded * with the active encoding and sent out. * Note: Returning an empty string will supress sending a mouse report, * which can be used to skip creating falsey reports in limited encodings * (DEFAULT only supports up to 223 1-based as coord value). */ export type CoreMouseEncoding = (event: ICoreMouseEvent) => string; /** * windowOptions */ export interface IWindowOptions { restoreWin?: boolean; minimizeWin?: boolean; setWinPosition?: boolean; setWinSizePixels?: boolean; raiseWin?: boolean; lowerWin?: boolean; refreshWin?: boolean; setWinSizeChars?: boolean; maximizeWin?: boolean; fullscreenWin?: boolean; getWinState?: boolean; getWinPosition?: boolean; getWinSizePixels?: boolean; getScreenSizePixels?: boolean; getCellSizePixels?: boolean; getWinSizeChars?: boolean; getScreenSizeChars?: boolean; getIconTitle?: boolean; getWinTitle?: boolean; pushTitle?: boolean; popTitle?: boolean; setWinLines?: boolean; } export interface IAnsiColorChangeEventColor { colorIndex: number; red: number; green: number; blue: number; } /** * Event fired for OSC 4 command - to change ANSI color based on its index. */ export interface IAnsiColorChangeEvent { colors: IAnsiColorChangeEventColor[]; } /** * Calls the parser and handles actions generated by the parser. */ export interface IInputHandler { onTitleChange: IEvent<string>; parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise<boolean>; print(data: Uint32Array, start: number, end: number): void; registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise<boolean>): IDisposable; registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise<boolean>): IDisposable; registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise<boolean>): IDisposable; registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable; /** C0 BEL */ bell(): void; /** C0 LF */ lineFeed(): void; /** C0 CR */ carriageReturn(): void; /** C0 BS */ backspace(): void; /** C0 HT */ tab(): void; /** C0 SO */ shiftOut(): void; /** C0 SI */ shiftIn(): void; /** CSI @ */ insertChars(params: IParams): void; /** CSI SP @ */ scrollLeft(params: IParams): void; /** CSI A */ cursorUp(params: IParams): void; /** CSI SP A */ scrollRight(params: IParams): void; /** CSI B */ cursorDown(params: IParams): void; /** CSI C */ cursorForward(params: IParams): void; /** CSI D */ cursorBackward(params: IParams): void; /** CSI E */ cursorNextLine(params: IParams): void; /** CSI F */ cursorPrecedingLine(params: IParams): void; /** CSI G */ cursorCharAbsolute(params: IParams): void; /** CSI H */ cursorPosition(params: IParams): void; /** CSI I */ cursorForwardTab(params: IParams): void; /** CSI J */ eraseInDisplay(params: IParams): void; /** CSI K */ eraseInLine(params: IParams): void; /** CSI L */ insertLines(params: IParams): void; /** CSI M */ deleteLines(params: IParams): void; /** CSI P */ deleteChars(params: IParams): void; /** CSI S */ scrollUp(params: IParams): void; /** CSI T */ scrollDown(params: IParams, collect?: string): void; /** CSI X */ eraseChars(params: IParams): void; /** CSI Z */ cursorBackwardTab(params: IParams): void; /** CSI ` */ charPosAbsolute(params: IParams): void; /** CSI a */ hPositionRelative(params: IParams): void; /** CSI b */ repeatPrecedingCharacter(params: IParams): void; /** CSI c */ sendDeviceAttributesPrimary(params: IParams): void; /** CSI > c */ sendDeviceAttributesSecondary(params: IParams): void; /** CSI d */ linePosAbsolute(params: IParams): void; /** CSI e */ vPositionRelative(params: IParams): void; /** CSI f */ hVPosition(params: IParams): void; /** CSI g */ tabClear(params: IParams): void; /** CSI h */ setMode(params: IParams, collect?: string): void; /** CSI l */ resetMode(params: IParams, collect?: string): void; /** CSI m */ charAttributes(params: IParams): void; /** CSI n */ deviceStatus(params: IParams, collect?: string): void; /** CSI p */ softReset(params: IParams, collect?: string): void; /** CSI q */ setCursorStyle(params: IParams, collect?: string): void; /** CSI r */ setScrollRegion(params: IParams, collect?: string): void; /** CSI s */ saveCursor(params: IParams): void; /** CSI u */ restoreCursor(params: IParams): void; /** CSI ' } */ insertColumns(params: IParams): void; /** CSI ' ~ */ deleteColumns(params: IParams): void; /** OSC 0 OSC 2 */ setTitle(data: string): void; /** OSC 4 */ setAnsiColor(data: string): void; /** ESC E */ nextLine(): void; /** ESC = */ keypadApplicationMode(): void; /** ESC > */ keypadNumericMode(): void; /** ESC % G ESC % @ */ selectDefaultCharset(): void; /** ESC ( C ESC ) C ESC * C ESC + C ESC - C ESC . C ESC / C */ selectCharset(collectAndFlag: string): void; /** ESC D */ index(): void; /** ESC H */ tabSet(): void; /** ESC M */ reverseIndex(): void; /** ESC c */ fullReset(): void; /** ESC n ESC o ESC | ESC } ESC ~ */ setgLevel(level: number): void; /** ESC # 8 */ screenAlignmentPattern(): void; } interface IParseStack { paused: boolean; cursorStartX: number; cursorStartY: number; decodedLength: number; position: number; }
the_stack
import { Abi, abiContract, AbiErrorCode, ParamsOfEncodeMessage, ResultOfProcessMessage, ResultOfRunTvm, signerKeys, TonClient, TvmErrorCode, } from "@tonclient/core"; import { Account } from "../account"; import { ContractPackage, contracts } from "../contracts"; import { expect, test } from "../jest"; import { ABIVersions, runner } from "../runner"; test.each(ABIVersions)("Test hello contract from docs.ton.dev (ABI v%i)", async (abiVersion) => { const { abi, processing, tvm, } = runner.getClient(); const helloAccount = await runner.getAccount(contracts.Hello, abiVersion); const helloAccountAddress = await helloAccount.getAddress(); await runner.deploy(helloAccount); await processing.process_message({ send_events: false, message_encode_params: { address: helloAccountAddress, abi: helloAccount.abi, call_set: { function_name: "touch", }, signer: helloAccount.signer, } }); helloAccount.dropCachedData(); const localResult1 = await run_tvm(helloAccount, "sayHello"); const localResult2 = await run_tvm(helloAccount, "sayHello"); expect(localResult1.decoded?.output?.value0) .toBeTruthy(); expect(localResult1.decoded?.output?.value0) .toEqual(localResult2.decoded?.output?.value0); // end of test, start of local functions async function run_tvm(account: Account, function_name: string) { const encodeResult = await abi.encode_message({ abi: account.abi, address: await account.getAddress(), call_set: { function_name, }, signer: account.signer, }); return await tvm.run_tvm({ abi: account.abi, account: await account.boc(), message: encodeResult.message, }) } }); test.each(ABIVersions)("Run aborted transaction (ABI v%i)", async (abiVersion) => { const { processing, } = runner.getClient(); const walletAccount = await runner.getAccount(contracts.WalletContract, abiVersion); const walletAccountAddress = await walletAccount.getAddress(); await runner.deploy(walletAccount); try { await processing.process_message({ send_events: false, message_encode_params: { address: walletAccountAddress, abi: walletAccount.abi, call_set: { function_name: "sendTransaction", input: { dest: "0:0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF", value: 0, bounce: false, }, }, signer: walletAccount.signer, } }); } catch (error: any) { expect(error.code).toEqual(TvmErrorCode.ContractExecutionError); expect(error.data.phase).toEqual("computeVm"); expect(error.data.transaction_id).toBeTruthy(); expect(error.data.exit_code).toEqual(101); } try { await processing.process_message({ send_events: false, message_encode_params: { address: walletAccountAddress, abi: walletAccount.abi, call_set: { function_name: "sendTransaction", input: {}, }, signer: walletAccount.signer, } }); } catch (error: any) { expect(error.code).toEqual(AbiErrorCode.EncodeRunMessageFailed); } }); test.each(ABIVersions)("External signing on ABI v%i", async (abiVersion) => { const { abi, crypto, } = runner.getClient(); const keys = await crypto.generate_random_sign_keys(); const eventsAccount = await runner.getAccount(contracts.Events, abiVersion); const eventsAccountAddress = await eventsAccount.getAddress(); const deployParams = { ...eventsAccount.getParamsOfDeployMessage(), call_set: { function_name: "constructor", header: { pubkey: keys.public, time: BigInt(1599458364291), expire: 1599458404, } } } const unsignedDeployMessage = await abi.encode_message({ ...deployParams, signer: { type: "External", public_key: keys.public, }, }); const signResult = await crypto.sign({ keys, unsigned: unsignedDeployMessage.data_to_sign!, }); const signedDeployMessage = await abi.attach_signature({ abi: deployParams.abi, message: unsignedDeployMessage.message, public_key: keys.public, signature: signResult.signature, }); const signedDeployMessage2 = await abi.encode_message({ ...deployParams, signer: { type: "Keys", keys }, }); expect(signedDeployMessage.message) .toEqual(signedDeployMessage2.message); const runMessageParams = { address: eventsAccountAddress, abi: eventsAccount.abi, call_set: { function_name: "returnValue", input: { id: "0" }, header: { pubkey: keys.public, time: BigInt(Date.now()), expire: Math.round(Date.now() / 1000) + 100, } }, }; const unsignedRunMessage = await abi.encode_message({ ...runMessageParams, signer: { type: "External", public_key: keys.public, }, }); const signRunMessageResult = await crypto.sign({ keys, unsigned: unsignedRunMessage.data_to_sign!, }); const signedRunMessage = await abi.attach_signature({ abi: runMessageParams.abi, message: unsignedRunMessage.message, public_key: keys.public, signature: signRunMessageResult.signature, }); const signedRunMessage2 = await abi.encode_message({ ...runMessageParams, signer: { type: "Keys", keys }, }); expect(signedRunMessage.message) .toEqual(signedRunMessage2.message); }); test("Test CheckInitParams contract double deployment with different init data", async () => { const { abi, tvm, } = runner.getClient(); const initData1 = { addressVariable: "0:fedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321", uintVariable: "0x0", booleanVariable: true, bytesVariable: await generateRandomBytesInHex(32), }; const checkInitParamsAccount1 = await runner.getAccount(contracts.CheckInitParams, 2, undefined, undefined, initData1); const checkInitParamsAccount1Address = await checkInitParamsAccount1.getAddress(); await runner.deploy(checkInitParamsAccount1); checkInitParamsAccount1.dropCachedData(); const initData2 = { addressVariable: "0:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", uintVariable: "0xffffffff", booleanVariable: false, bytesVariable: await generateRandomBytesInHex(64), }; const checkInitParamsAccount2 = await runner.getAccount(contracts.CheckInitParams, 2, undefined, undefined, initData2); const checkInitParamsAccount2Address = await checkInitParamsAccount2.getAddress(); await runner.deploy(checkInitParamsAccount2); expect(checkInitParamsAccount1Address) .not.toEqual(checkInitParamsAccount2Address); const addressResult1 = await run_tvm(checkInitParamsAccount1, "getAddressVariable"); const addressResult2 = await run_tvm(checkInitParamsAccount2, "getAddressVariable"); expect(addressResult1.decoded?.output).toEqual({ value0: initData1.addressVariable, }); expect(addressResult2.decoded?.output).toEqual({ value0: initData2.addressVariable, }); const uintResult1 = await run_tvm(checkInitParamsAccount1, "getUintVariable"); const uintResult2 = await run_tvm(checkInitParamsAccount2, "getUintVariable"); expect(uintResult1.decoded?.output).toEqual({ value0: "0x" + TonClient.toHex(initData1.uintVariable, 256), }); expect(uintResult2.decoded?.output).toEqual({ value0: "0x" + TonClient.toHex(initData2.uintVariable, 256), }); const booleanResult1 = await run_tvm(checkInitParamsAccount1, "getBooleanVariable"); const booleanResult2 = await run_tvm(checkInitParamsAccount2, "getBooleanVariable"); expect(booleanResult1.decoded?.output).toEqual({ value0: initData1.booleanVariable, }); expect(booleanResult2.decoded?.output).toEqual({ value0: initData2.booleanVariable, }); const bytesResult1 = await run_tvm(checkInitParamsAccount1, "getBytesVariable"); const bytesResult2 = await run_tvm(checkInitParamsAccount2, "getBytesVariable"); expect(bytesResult1.decoded?.output).toEqual({ value0: initData1.bytesVariable, }); expect(bytesResult2.decoded?.output).toEqual({ value0: initData2.bytesVariable, }); // end of test, start of local functions async function generateRandomBytesInHex(length: number): Promise<string> { var randomBytesInBase64 = await runner.getClient() .crypto.generate_random_bytes({ length, }); return Buffer.from(randomBytesInBase64.bytes, "base64").toString("hex"); } async function run_tvm(account: Account, function_name: string): Promise<ResultOfRunTvm> { return await tvm.run_tvm({ abi: account.abi, account: await account.boc(), message: (await abi.encode_message({ abi: account.abi, address: await account.getAddress(), signer: account.signer, call_set: { function_name, } })).message, }); } }); test.each(ABIVersions)("Test SetCode contracts (ABI v%i)", async (abiVersion) => { const { boc, processing, } = runner.getClient(); const setCodeAccount = await runner.getAccount(contracts.Setcode, abiVersion); const setCode2ContractPackage = getContractPackage(contracts.Setcode2, abiVersion); await runner.deploy(setCodeAccount); const version1 = await run(setCodeAccount, setCodeAccount.abi, "getVersion"); expect (version1.decoded?.output?.value0) .toEqual("0x0000000000000000000000000000000000000000000000000000000000000001"); await run(setCodeAccount, setCodeAccount.abi, "main", { newcode: (await boc.get_code_from_tvc({ tvc: setCode2ContractPackage.tvc })).code }); const version2 = await run(setCodeAccount, abiContract(setCode2ContractPackage.abi), "getNewVersion"); expect (version2.decoded?.output?.value0) .toEqual("0x0000000000000000000000000000000000000000000000000000000000000002"); // end of test, start of local functions function getContractPackage(packages: { [abiVersion: number]: ContractPackage }, abiVersion: any): ContractPackage { const pkg: ContractPackage | undefined = packages[Number(abiVersion)]; if (!pkg) { throw new Error(`Missing required contract with ABI v${abiVersion}`); } return pkg; } async function run(account: Account, abi: Abi, function_name: string, input?: any): Promise<ResultOfProcessMessage> { return await processing.process_message({ message_encode_params: { abi: abi, signer: account.signer, address: await account.getAddress(), call_set: { function_name, input, }, }, send_events: false, }); } }); test("Test expire retries", async () => { const processing = runner.getClient().processing; const helloAccount = await runner.getAccount(contracts.Hello, 2); const helloAccountAddress = await helloAccount.getAddress(); await runner.deploy(helloAccount); let completed = 0; const run = async () => { const result = await processing.process_message({ message_encode_params: { abi: helloAccount.abi, signer: helloAccount.signer, address: helloAccountAddress, call_set: { function_name: "touch" } }, send_events: false, }); console.log(`>>> run complete ${++completed}`); return result; }; const runs = []; for (let i = 0; i < 10; i += 1) { runs.push(run()); } await Promise.all(runs); }); test("Signing", async () => { const { abi, crypto, processing, } = runner.getClient(); const ownerKeys = await crypto.generate_random_sign_keys(); const deployKeys = await crypto.generate_random_sign_keys(); const time = Math.round((Date.now() + 10000) / 1000); const sensorAccountAbi = abiContract(contracts.Sensor[2].abi); const sensorAccountTvc = contracts.Sensor[2].tvc; const paramsOfDeployMessage: ParamsOfEncodeMessage = { abi: sensorAccountAbi, signer: signerKeys(deployKeys), deploy_set: { tvc: sensorAccountTvc, }, call_set: { function_name: "constructor", input: { ownerKey: `0x${ownerKeys.public}` }, header: { time: BigInt(time), } }, }; const futureAddress = (await abi.encode_message(paramsOfDeployMessage)).address; await runner.sendGramsTo(futureAddress); const deployResult = await processing.process_message({ message_encode_params: { ...paramsOfDeployMessage, call_set: { function_name: "constructor", input: { ownerKey: `0x${ownerKeys.public}` }, // without header }, }, send_events: false, }); const helloAddress: string = deployResult.transaction.account_addr; await processing.process_message({ message_encode_params: { address: helloAddress, abi: sensorAccountAbi, call_set: { function_name: "setData", input: { input: 8, }, }, signer: signerKeys(ownerKeys), }, send_events: false, }); });
the_stack
import { NxFormfieldHintDirective } from './hint.directive'; import { Component, Type, ViewChild, ChangeDetectionStrategy, Directive } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick, inject, waitForAsync } from '@angular/core/testing'; import { FormGroup, ReactiveFormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms'; import { NxInputModule, NxInputDirective } from '@aposin/ng-aquila/input'; import { NxFormfieldComponent, AppearanceType, FORMFIELD_DEFAULT_OPTIONS, FloatLabelType, FormfieldDefaultOptions } from './formfield.component'; import { NxFormfieldNoteDirective } from './note.directive'; import { NxFormfieldErrorDirective } from './error.directive'; const formfieldDefaultOptions: FormfieldDefaultOptions = { appearance: 'outline', nxFloatLabel: 'always' }; // NxInputModule also imports NxFormfieldModule // For better readablity here, We can safely ignore some conventions in our specs // tslint:disable:component-class-suffix @Directive() abstract class FormfieldTest { @ViewChild(NxFormfieldComponent) textfieldInstance!: NxFormfieldComponent; @ViewChild(NxInputDirective) inputInstance!: NxInputDirective; @ViewChild(NxFormfieldErrorDirective) formfieldError!: NxFormfieldErrorDirective; @ViewChild(NxFormfieldNoteDirective) formfieldNote!: NxFormfieldNoteDirective; @ViewChild(NxFormfieldHintDirective) formfieldHint!: NxFormfieldHintDirective; testForm!: FormGroup; currentValue: any; appearance!: AppearanceType; floatLabel!: FloatLabelType; disabled: boolean = false; readonly: boolean = false; } describe('NxFormfieldComponent', () => { let fixture: ComponentFixture<FormfieldTest>; let formfieldInstance: NxFormfieldComponent; let testInstance: FormfieldTest; let formfieldElement: HTMLElement; let inputElement: HTMLElement; let labelElement: HTMLLabelElement; function createTestComponent(component: Type<FormfieldTest>) { fixture = TestBed.createComponent(component); fixture.detectChanges(); testInstance = fixture.componentInstance; formfieldElement = fixture.nativeElement.querySelector('nx-formfield'); inputElement = fixture.nativeElement.querySelector('.c-input'); labelElement = fixture.nativeElement.querySelector('.nx-formfield__label'); formfieldInstance = testInstance.textfieldInstance; } function fillWithContent(value: any) { testInstance.currentValue = value; // this round will assign it through ngModel to the input directly fixture.detectChanges(); tick(); // Input Control is updated by now. Now propagate a next round of changes, // so that the formfield can update itself fixture.detectChanges(); tick(); } describe('basic', () => { beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [ReactiveFormsModule, FormsModule, NxInputModule], declarations: [ BasicFormfield, NoInputFormfield, DirectivesFormfield, ErrorFormfield, NoteFormfield, NgModelFormfield, FloatingFormfield, CustomLabelAndInputFormfield, CustomLabelFormfield, OutlineFormfield, OnPushFormfield, NativeSelectFormfield, ConditionalInputComponent ] }).compileComponents(); }) ); it('creates a formfield', () => { createTestComponent(BasicFormfield); expect(testInstance).toBeTruthy(); }); // bug Expression has changed after it was checked it('does not throw an error when the control is conditionally loaded', () => { expect(() => { createTestComponent(ConditionalInputComponent); }).not.toThrowError(); }); it('enforces NxFormfieldControl presence', () => { expect(() => { createTestComponent(NoInputFormfield); }).toThrowError('Formfield must contain a NxFormfieldControl like input[nxInput] or a custom implementation'); }); it('display a given prefix', () => { createTestComponent(DirectivesFormfield); expect(fixture.nativeElement.textContent).toContain('content-prefix'); }); it('display a given suffix', () => { createTestComponent(DirectivesFormfield); expect(fixture.nativeElement.textContent).toContain('content-suffix'); }); it('display a given appendix', () => { createTestComponent(DirectivesFormfield); expect(fixture.nativeElement.textContent).toContain('content-appendix'); }); it('display a given hint', () => { createTestComponent(DirectivesFormfield); expect(fixture.nativeElement.textContent).toContain('content-hint'); }); it('display a given label via `nx-formfield-label`', () => { createTestComponent(CustomLabelFormfield); expect(fixture.nativeElement.textContent).toContain('Label'); }); it('prefers a label directive over label input', () => { createTestComponent(CustomLabelAndInputFormfield); expect(fixture.nativeElement.textContent).toEqual('directiveLabel'); }); it('doesn\'t show the error by default', () => { createTestComponent(DirectivesFormfield); expect(fixture.nativeElement.textContent).not.toContain('content-error'); }); it( 'reflects filled state in css', fakeAsync(() => { createTestComponent(NgModelFormfield); fillWithContent('fill with content'); expect(formfieldElement.classList.contains('is-filled')).toBe(true); }) ); it('assigns the label', () => { createTestComponent(BasicFormfield); expect(fixture.nativeElement.textContent).toContain('Given Label'); }); it( 'floats the label when filled', fakeAsync(() => { createTestComponent(NgModelFormfield); fillWithContent('fill with content'); expect(formfieldElement.classList.contains('is-floating')).toBe(true); }) ); it('always floats the label when floatLabel is set to "always"', () => { createTestComponent(FloatingFormfield); testInstance.floatLabel = 'always'; fixture.detectChanges(); expect(formfieldElement.classList.contains('is-floating')).toBe(true); } ); // The former value of 1.6rem for the translateY transition on the elemen ..nx-formfield__label // was calculated es 19.2px. This caused a jumping label after the transition- but only in Firefox 61 and previous. // Probably because Firefox switches back from the GPU where subpixels are rendered without any issues // After the transition the value snaps back to 19px and we saw the 0.2px as a small jump // This is kind of testing the CSS but let's see if this test saves us // from getting into this issue again. This will test with Chrome (where we did not habe this issue) // but the underlying calculations we test are the same. // In case you wonder: We do not need to explicitly wait for the label float up, a single Angular tick // is enough to populate the calucalted matrix value. it('vertical translation required to float the label has no subpixels', fakeAsync(() => { createTestComponent(NgModelFormfield); fillWithContent('fill with content'); const floatingLabel = formfieldElement.querySelector('.nx-formfield__label'); const floatingLabelStyles = window.getComputedStyle(floatingLabel as Element); const caluclatedMatrix = floatingLabelStyles.webkitTransform; expect(caluclatedMatrix).toBe('matrix(1, 0, 0, 1, 0, -16)'); }) ); it( 'reflects control error state in css', fakeAsync(() => { createTestComponent(ErrorFormfield); testInstance.inputInstance.ngControl.control!.markAsTouched(); fixture.detectChanges(); tick(); expect(formfieldElement.classList.contains('has-error')).toBe(true); }) ); it( 'shows the error instead of a given note', fakeAsync(() => { createTestComponent(ErrorFormfield); fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toContain('content-error'); expect(fixture.nativeElement.textContent).toContain('content-note'); testInstance.inputInstance.ngControl.control!.markAsTouched(); fixture.detectChanges(); tick(); fixture.detectChanges(); tick(); expect(testInstance.inputInstance.errorState).toBeTruthy(); expect(fixture.nativeElement.textContent).toContain('content-error'); expect(fixture.nativeElement.textContent).not.toContain('content-note'); } )); it( 'keeps the note without an error message available', fakeAsync(() => { createTestComponent(NoteFormfield); expect(fixture.nativeElement.textContent).toContain('content-note'); testInstance.inputInstance.ngControl.control!.markAsTouched(); fixture.detectChanges(); tick(); expect(fixture.nativeElement.textContent).toContain('content-note'); }) ); it('should render the formfield with no outline on default', () => { createTestComponent(BasicFormfield); expect(fixture.nativeElement.classList).not.toContain('has-outline'); } ); it('should display the formfield with the correct appearance', () => { createTestComponent(OutlineFormfield); expect(formfieldElement.classList).not.toContain('has-outline'); fixture.componentInstance.appearance = 'outline'; fixture.detectChanges(); expect(formfieldElement.classList).toContain('has-outline'); fixture.componentInstance.appearance = 'auto'; fixture.detectChanges(); expect(formfieldElement.classList).not.toContain('has-outline'); }); it('should add is-disabled class when control is disabled', () => { createTestComponent(BasicFormfield); expect(formfieldElement.classList).not.toContain('is-disabled'); testInstance.disabled = true; fixture.detectChanges(); expect(formfieldElement.classList).toContain('is-disabled'); }); it('should add is-readonly class when control is readonly', () => { createTestComponent(BasicFormfield); expect(formfieldElement.classList).not.toContain('is-readonly'); testInstance.readonly = true; fixture.detectChanges(); expect(formfieldElement.classList).toContain('is-readonly'); }); describe('programmatic tests', () => { it('updates on appearance change', () => { createTestComponent(OnPushFormfield); expect(formfieldElement.classList).not.toContain('has-outline'); formfieldInstance.appearance = 'outline'; fixture.detectChanges(); expect(formfieldElement.classList).toContain('has-outline'); formfieldInstance.appearance = 'auto'; fixture.detectChanges(); expect(formfieldElement.classList).not.toContain('has-outline'); } ); }); describe('a11y', () => { it('has no accessibility violations', async () => { createTestComponent(BasicFormfield); await expectAsync(fixture.nativeElement).toBeAccessible(); }); it('adds hints to aria described by', fakeAsync(() => { createTestComponent(DirectivesFormfield); tick(); fixture.detectChanges(); let ariaDescribedBy; ariaDescribedBy = inputElement.attributes.getNamedItem('aria-describedby')!.value; tick(); fixture.detectChanges(); expect(ariaDescribedBy).toContain(testInstance.formfieldHint.id); })); it('updates described by with the error id', fakeAsync(() => { let ariaDescribedBy; createTestComponent(ErrorFormfield); fixture.detectChanges(); tick(); fixture.detectChanges(); tick(); // before only the not id is set ariaDescribedBy = inputElement.attributes.getNamedItem('aria-describedby')!.value; expect(ariaDescribedBy).toBe(testInstance.formfieldNote.id); testInstance.inputInstance.ngControl.control!.markAsTouched(); fixture.detectChanges(); tick(); fixture.detectChanges(); tick(); // the error id should join the list of describedBy ids. ariaDescribedBy = inputElement.attributes.getNamedItem('aria-describedby')!.value; expect(ariaDescribedBy).toBe(testInstance.formfieldError.id); }) ); it('updates aria-owns and attribute for to the control id', () => { createTestComponent(BasicFormfield); const ariaOwns = labelElement.attributes.getNamedItem('aria-owns')!.value; const attrFor = labelElement.attributes.getNamedItem('for')!.value; expect(ariaOwns).toBe(testInstance.inputInstance.id); expect(attrFor).toBe(testInstance.inputInstance.id); } ); }); describe('Native Select', () => { it('Should create a formfield with a Native select', () => { createTestComponent(NativeSelectFormfield); expect(testInstance).toBeTruthy(); }); }); it('should have an "auto" appearance if no default options are provided', () => { createTestComponent(OutlineFormfield); expect(testInstance.textfieldInstance.appearance).toBe('auto'); expect(formfieldElement.classList).not.toContain('has-outline'); }); it('should have an "auto" floatingLabel if no default options are provided', () => { createTestComponent(OutlineFormfield); expect(testInstance.textfieldInstance.floatLabel).toBe('auto'); expect(formfieldElement.classList).not.toContain('is-floating'); }); }); describe('Default options', () => { beforeEach(waitForAsync(() => { formfieldDefaultOptions.appearance = 'outline'; formfieldDefaultOptions.nxFloatLabel = 'always'; TestBed.configureTestingModule({ imports: [ReactiveFormsModule, FormsModule, NxInputModule], declarations: [ BasicFormfield, OutlineFormfield, FloatingFormfield ], providers: [ { provide: FORMFIELD_DEFAULT_OPTIONS, useValue: formfieldDefaultOptions } ] }).compileComponents(); })); it('should have an "auto" appearance if empty default options are provided', inject([FORMFIELD_DEFAULT_OPTIONS], (defaultOptions: FormfieldDefaultOptions) => { delete defaultOptions.appearance; createTestComponent(BasicFormfield); expect(testInstance.textfieldInstance.appearance).toBe('auto'); expect(formfieldElement.classList).not.toContain('has-outline'); }) ); it('should have an "auto" floatingLabel if empty default options are provided', inject([FORMFIELD_DEFAULT_OPTIONS], (defaultOptions: FormfieldDefaultOptions) => { delete defaultOptions.nxFloatLabel; createTestComponent(BasicFormfield); expect(testInstance.textfieldInstance.floatLabel).toBe('auto'); expect(formfieldElement.classList).not.toContain('is-floating'); }) ); it('should have a custom default appearance if default options contain a custom appearance', () => { createTestComponent(BasicFormfield); expect(testInstance.textfieldInstance.appearance).toBe('outline'); expect(formfieldElement.classList).toContain('has-outline'); }); it('should have a custom default floatingLabel if default options contain a custom floatLabel', () => { createTestComponent(BasicFormfield); expect(testInstance.textfieldInstance.floatLabel).toBe('always'); expect(formfieldElement.classList).toContain('is-floating'); }); it('should override a custom default appearance', () => { createTestComponent(OutlineFormfield); expect(testInstance.textfieldInstance.appearance).toBe('outline'); fixture.componentInstance.appearance = 'auto'; fixture.detectChanges(); expect(testInstance.textfieldInstance.appearance).toBe('auto'); expect(formfieldElement.classList).not.toContain('has-outline'); }); it('should override a custom default floatLabel', () => { createTestComponent(FloatingFormfield); expect(testInstance.textfieldInstance.floatLabel).toBe('always'); testInstance.floatLabel = 'auto'; fixture.detectChanges(); expect(testInstance.textfieldInstance.floatLabel).toBe('auto'); expect(formfieldElement.classList).not.toContain('is-floating'); }); it('changes the appearance on injection token change', inject([FORMFIELD_DEFAULT_OPTIONS], (defaultOptions: FormfieldDefaultOptions) => { createTestComponent(BasicFormfield); expect(testInstance.textfieldInstance.appearance).toBe('outline'); expect(formfieldElement.classList).toContain('has-outline'); defaultOptions.appearance = 'auto'; fixture.detectChanges(); expect(testInstance.textfieldInstance.appearance).toBe('auto'); expect(formfieldElement.classList).not.toContain('has-outline'); }) ); it('changes floatLabel on injection token change', inject([FORMFIELD_DEFAULT_OPTIONS], (defaultOptions: FormfieldDefaultOptions) => { createTestComponent(BasicFormfield); expect(testInstance.textfieldInstance.floatLabel).toBe('always'); expect(formfieldElement.classList).toContain('is-floating'); defaultOptions.nxFloatLabel = 'auto'; fixture.detectChanges(); expect(testInstance.textfieldInstance.floatLabel).toBe('auto'); expect(formfieldElement.classList).not.toContain('is-floating'); }) ); }); }); @Component({ template: ` <nx-formfield nxLabel="Given Label"> <input nxInput [disabled]="disabled" [readonly]="readonly"> </nx-formfield> ` }) class BasicFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield></nx-formfield> ` }) class NoInputFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield> <nx-formfield-label>Label</nx-formfield-label> <input nxInput> </nx-formfield> ` }) class CustomLabelFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield> <input nxInput> <span nxFormfieldPrefix>content-prefix</span> <span nxFormfieldSuffix>content-suffix</span> <span nxFormfieldHint>content-hint</span> <span nxFormfieldNote>content-note</span> <span nxFormfieldError>content-error</span> <span nxFormfieldAppendix>content-appendix</span> </nx-formfield> ` }) class DirectivesFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield> <input nxInput required [(ngModel)]="currentValue"> <span nxFormfieldNote>content-note</span> <span nxFormfieldError>content-error</span> </nx-formfield> ` }) class ErrorFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield> <input nxInput required [(ngModel)]="currentValue"> <span nxFormfieldNote>content-note</span> </nx-formfield> ` }) class NoteFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield nxLabel='Given Label'> <input nxInput [(ngModel)]="currentValue"> </nx-formfield> ` }) class NgModelFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield [nxFloatLabel]='floatLabel'> <input nxInput [(ngModel)]="currentValue"> </nx-formfield> ` }) class FloatingFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield> <select nxInput> <option></option> <option>Snoopy</option> <option>Charlie brown</option> <option>Sally Brown</option> </select> </nx-formfield> ` }) class NativeSelectFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield nxLabel='inputLabel'> <nx-formfield-label>directiveLabel</nx-formfield-label> <input nxInput> </nx-formfield> ` }) class CustomLabelAndInputFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield [appearance]="appearance"> <input nxInput> </nx-formfield> ` }) class OutlineFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield [appearance]="appearance"> <input nxInput> </nx-formfield>`, changeDetection: ChangeDetectionStrategy.OnPush }) class OnPushFormfield extends FormfieldTest {} @Component({ template: ` <nx-formfield nxLabel="IBAN"> <input *ngIf="true" nxInput/> <span nxFormfieldHint>my hint</span> </nx-formfield>` }) class ConditionalInputComponent extends FormfieldTest { }
the_stack
export interface Breakpoints { /** * Tablet: 740px */ medium: number; /** * Desktop: 980px */ large: number; /** * Desktop HD: 1200px */ xLarge: number; /** * Desktop Full HD: 1800px */ max: number; } export interface AccordionCardStyling { /** * Border color in closed state. */ borderColor: string; /** * Border color in opened state. */ openedBorderColor: string; /** * Border of header block when card is expanded. */ openedHeaderBorderColor: string; /** * Background of header block when card is expanded. */ openedHeaderBackground: string; /** * Background of header block when card is not expanded. */ headerBackground: string; /** * Padding of header block. */ headerPadding: string; } export interface MetroInfoTileStyling { /** * MetroInfoTile text color. */ textColor: string; /** * MetroInfoTile background color. */ background: string; /** * MetroInfoTile size (will always be square, size x size). */ size: string; } export interface FlyoutStyling { /** * Flyout maximum width. */ maxWidth: string; /** * Flyout maximum height. */ maxHeight: string; /** * Flyout backgound color. */ background: string; /** * Flyout text color. */ textColor: string; /** * Flyout text font size. */ fontSize: string; /** * Flyout arrow size */ arrowSize: number; } export interface ButtonThemeSettings { /** * Color of a button background. */ background: string; /** * Color of a hoveredbutton background. */ hoverBackground: string; /** * Color of a focused button background. */ focusBackground: string; /** * Color of a disabled button background. */ disabledBackground: string; /** * Color of the text in a button. */ text: string; /** * Color of the text in a hovered button. */ hoverText: string; /** * Color of the text in a focused button. */ focusText: string; /** * Color of the text in a disabled button. */ disabledText: string; /** * Border of a button. */ border: string; /** * Border of a hovered button. */ hoverBorder: string; /** * Border of a focused button. */ focusBorder: string; /** * Border of a disabled button. */ disabledBorder: string; /** * Line height of a medium (default) button. */ lineHeightMedium: string; /** * Line height of a small button. */ lineHeightSmall: string; } export interface ActionButtonThemeSettings { /** * Color of icon background. */ iconBackground: string; /** * Color of icon background when hovered. */ hoverIconBackground: string; /** * Color of icon background when focused. */ focusIconBackground: string; } export type PreciseThemeColors = { /** * Theme color UI0. */ ui0: string; /** * Theme color UI1. */ ui1: string; /** * Theme color UI2. */ ui2: string; /** * Theme color UI3. */ ui3: string; /** * Theme color UI4. */ ui4: string; /** * Theme color UI5. */ ui5: string; /** * Theme color UI6. */ ui6: string; /** * Theme color UI7. */ ui7: string; /** * Theme color UI8. */ ui8: string; /** * Theme color TEXT0. */ text0: string; /** * Theme color TEXT1. */ text1: string; /** * Theme color TEXT2. */ text2: string; /** * Theme color TEXT3. */ text3: string; /** * Theme color TEXT4. */ text4: string; /** * Theme color TEXT5. */ text5: string; /** * Theme color TEXT6, which is the color of ordinary text. */ text6: string; /** * Theme color TEXT7. */ text7: string; }; export interface PreciseFullTheme extends PreciseThemeColors { /** * Padding for accordion items header. */ accordionPadding: string; /** * Padding for accordion items content. */ accordionContentPadding: string; /** * Accordion bottom border definition. */ accordionLine: string; /** * Colors of the primary button. */ buttonPrimary: ButtonThemeSettings; /** * Colors of the secondary button. */ buttonSecondary: ButtonThemeSettings; /** * Colors of the warning action button. */ actionButtonWarning: ActionButtonThemeSettings; /** * Position of the icon when place inside a button. */ buttonIconPosition: 'left' | 'right'; /** * Primary color to use. */ primary: string; /** * Secondary color to use. */ secondary: string; /** * Color of disabled text. */ textDisabled: string; /** * Color of a disabled input background. */ inputDisabled: string; /** * Color of an input error. */ inputError: string; /** * Colors to be used cyclically. */ colorCycle: Array<string>; /** * General font family to use. */ fontFamily: string; /** * Padding for headings h1-h6. */ headingsPadding: string; /** * Table border. */ tableBorder: string; /** * Layout for the table. */ tableLayout: string; /** * Padding value for table header row. */ tableHeadPadding: string; /** * Background color for ZeissletCard tags. */ tagBackground: string; /** * Font color for ZeissletCard tags. */ tagColor: string; /** * The color of the badge. */ badgeColor: string; /** * The background of the badge. */ badgeBackground: string; /** * The background of the Toggle Head. */ toggleHeadBackground: string; /** * The background of the active Toggle Head. */ toggleHeadActiveBackground: string; /** * Breakpoint values for the responsive design. */ breakpoints: Breakpoints; /** * Color of not specified notification, */ notificationColorNone: string; /** * Color of success notification, */ notificationColorSuccess: string; /** * Color of info notification, */ notificationColorInfo: string; /** * Color of warning notification, */ notificationColorWarning: string; /** * Color of error notification, */ notificationColorError: string; /** * Notification padding. */ notificationPadding: string; /** * Notification box shadow. */ notificationBoxShadow: string; /** * Notification border width. */ notificationBorderWidth: string; /** * Notification title font size. */ notificationTitleFontSize: string; /** * Notification title line height. */ notificationTitleLineHeight: string; /** * Notification text font size. */ notificationTextFontSize: string; /** * Notification text line height. */ notificationTextLineHeight: string; /** * Notification icon margin right. */ notificationIconMarginRight: string; /** * Specific Flyout theme settings. */ flyout: FlyoutStyling; /** * Specific MetroInfoTile theme settings. */ metroInfoTile: MetroInfoTileStyling; /** * Specific AccordionCard theme settings. */ accordionCard: AccordionCardStyling; /** * Color of highlighted text */ highlightColor: string; } export type PreciseTheme = { [T in keyof PreciseFullTheme]?: Partial<PreciseFullTheme[T]> }; export interface StandardProps { /** * Places the given class on the element. */ className?: string; /** * An optional theme which can be passed down to a component. */ theme?: PreciseTheme; /** * The style prop for explicitly overriding some CSS styles. */ style?: React.CSSProperties; } export interface InputChangeEvent<T> { /** * The current value of the input field. */ value: T; /** * Original change event */ originalEvent?: React.ChangeEvent<any>; } export interface InputProps<T> extends StandardProps { /** * Sets the component as disabled. */ disabled?: boolean; /** * The current value of the input, leading to a controlled field. */ value?: T; /** * The initial value of the input. */ defaultValue?: T; /** * Event emitted once the value changes due to user input. */ onChange?(e: InputChangeEvent<T>): void; /** * Event triggered once the input gets focused. */ onFocus?(): void; /** * Event triggered once the input loses the focus. */ onBlur?(): void; /** * Event triggered when a key was pressed. */ onInput?(e?: InputChangeEvent<string>): void; /** * Optional name if to be used within a form context. */ name?: string; /** * Displays the error message below the input. */ error?: React.ReactChild; /** * Displays the info message below the input. Only applies if * no error is to be shown. */ info?: React.ReactChild; /** * Sets if the input should immediately receive focus. */ autoFocus?: boolean; /** * Sets the autocomplete mode of the input. */ autoComplete?: 'on' | 'off'; /** * Sets type on the input field. */ type?: string; /** * Sets maximum lenngth of input field. */ maxLength?: number; } export interface LabeledInputProps<T> extends InputProps<T> { /** * Sets the text of label. * @default '' */ label?: React.ReactChild; /** * A hint to the user of what can be entered in the control. * The placeholder text must not contain carriage returns or line-feeds. * @default '' */ placeholder?: string; } export interface TextInputProps extends LabeledInputProps<string> { /** * Removes the border of the text field. * @default false */ borderless?: boolean; /** * Sets the optional prefix of the input to show (e.g., "http://"). * @default null */ prefix?: React.ReactChild; /** * Sets the optional suffix of the input to show (e.g., "EUR"). * @default null */ suffix?: React.ReactChild; /** * Sets an optional default icon (if any) to use when no error or * clearable is given. */ icon?: React.ReactChild; } export interface RefProps { /** * Callback to be used to get the referenced DOM node. * @param node The node that is used. */ innerRef?(node: HTMLElement | null): void; } export const ScreenSizeList = stringLiteralArray(['small', 'medium', 'large', 'xLarge', 'max']); export type ScreenSize = typeof ScreenSizeList[number]; // Helper type operators export type KeyofBase = keyof any; export type Diff<T extends KeyofBase, U extends KeyofBase> = ({ [P in T]: P } & { [P in U]: never } & { [x: string]: never })[T]; export type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>; export type Component<P> = React.ComponentClass<P> | React.StatelessComponent<P>; // Helper type functions function stringLiteralArray<T extends string>(val: Array<T>) { return val; }
the_stack
import { SnapshotVersion } from '../core/snapshot_version'; import { ResourcePath } from '../model/path'; import { debugAssert, hardAssert } from '../util/assert'; import { BATCHID_UNKNOWN } from '../util/types'; import { decodeResourcePath, encodeResourcePath } from './encoded_resource_path'; import { dbDocumentSize, removeMutationBatch } from './indexeddb_mutation_batch_impl'; import { DbBundle, DbClientMetadata, DbCollectionParent, DbCollectionParentKey, DbDocumentMutation, DbDocumentMutationKey, DbMutationBatch, DbMutationBatchKey, DbMutationQueue, DbMutationQueueKey, DbNamedQuery, DbPrimaryClient, DbRemoteDocument, DbRemoteDocumentGlobal, DbRemoteDocumentGlobalKey, DbRemoteDocumentKey, DbTarget, DbTargetDocument, DbTargetDocumentKey, DbTargetGlobal, DbTargetGlobalKey, DbTargetKey, SCHEMA_VERSION } from './indexeddb_schema'; import { fromDbMutationBatch, fromDbTarget, LocalSerializer, toDbTarget } from './local_serializer'; import { MemoryCollectionParentIndex } from './memory_index_manager'; import { PersistencePromise } from './persistence_promise'; import { SimpleDbSchemaConverter, SimpleDbTransaction } from './simple_db'; /** Performs database creation and schema upgrades. */ export class SchemaConverter implements SimpleDbSchemaConverter { constructor(private readonly serializer: LocalSerializer) {} /** * Performs database creation and schema upgrades. * * Note that in production, this method is only ever used to upgrade the schema * to SCHEMA_VERSION. Different values of toVersion are only used for testing * and local feature development. */ createOrUpgrade( db: IDBDatabase, txn: IDBTransaction, fromVersion: number, toVersion: number ): PersistencePromise<void> { hardAssert( fromVersion < toVersion && fromVersion >= 0 && toVersion <= SCHEMA_VERSION, `Unexpected schema upgrade from v${fromVersion} to v${toVersion}.` ); const simpleDbTransaction = new SimpleDbTransaction('createOrUpgrade', txn); if (fromVersion < 1 && toVersion >= 1) { createPrimaryClientStore(db); createMutationQueue(db); createQueryCache(db); createRemoteDocumentCache(db); } // Migration 2 to populate the targetGlobal object no longer needed since // migration 3 unconditionally clears it. let p = PersistencePromise.resolve(); if (fromVersion < 3 && toVersion >= 3) { // Brand new clients don't need to drop and recreate--only clients that // potentially have corrupt data. if (fromVersion !== 0) { dropQueryCache(db); createQueryCache(db); } p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction)); } if (fromVersion < 4 && toVersion >= 4) { if (fromVersion !== 0) { // Schema version 3 uses auto-generated keys to generate globally unique // mutation batch IDs (this was previously ensured internally by the // client). To migrate to the new schema, we have to read all mutations // and write them back out. We preserve the existing batch IDs to guarantee // consistency with other object stores. Any further mutation batch IDs will // be auto-generated. p = p.next(() => upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction) ); } p = p.next(() => { createClientMetadataStore(db); }); } if (fromVersion < 5 && toVersion >= 5) { p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction)); } if (fromVersion < 6 && toVersion >= 6) { p = p.next(() => { createDocumentGlobalStore(db); return this.addDocumentGlobal(simpleDbTransaction); }); } if (fromVersion < 7 && toVersion >= 7) { p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction)); } if (fromVersion < 8 && toVersion >= 8) { p = p.next(() => this.createCollectionParentIndex(db, simpleDbTransaction) ); } if (fromVersion < 9 && toVersion >= 9) { p = p.next(() => { // Multi-Tab used to manage its own changelog, but this has been moved // to the DbRemoteDocument object store itself. Since the previous change // log only contained transient data, we can drop its object store. dropRemoteDocumentChangesStore(db); createRemoteDocumentReadTimeIndex(txn); }); } if (fromVersion < 10 && toVersion >= 10) { p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction)); } if (fromVersion < 11 && toVersion >= 11) { p = p.next(() => { createBundlesStore(db); createNamedQueriesStore(db); }); } return p; } private addDocumentGlobal( txn: SimpleDbTransaction ): PersistencePromise<void> { let byteCount = 0; return txn .store<DbRemoteDocumentKey, DbRemoteDocument>(DbRemoteDocument.store) .iterate((_, doc) => { byteCount += dbDocumentSize(doc); }) .next(() => { const metadata = new DbRemoteDocumentGlobal(byteCount); return txn .store<DbRemoteDocumentGlobalKey, DbRemoteDocumentGlobal>( DbRemoteDocumentGlobal.store ) .put(DbRemoteDocumentGlobal.key, metadata); }); } private removeAcknowledgedMutations( txn: SimpleDbTransaction ): PersistencePromise<void> { const queuesStore = txn.store<DbMutationQueueKey, DbMutationQueue>( DbMutationQueue.store ); const mutationsStore = txn.store<DbMutationBatchKey, DbMutationBatch>( DbMutationBatch.store ); return queuesStore.loadAll().next(queues => { return PersistencePromise.forEach(queues, (queue: DbMutationQueue) => { const range = IDBKeyRange.bound( [queue.userId, BATCHID_UNKNOWN], [queue.userId, queue.lastAcknowledgedBatchId] ); return mutationsStore .loadAll(DbMutationBatch.userMutationsIndex, range) .next(dbBatches => { return PersistencePromise.forEach( dbBatches, (dbBatch: DbMutationBatch) => { hardAssert( dbBatch.userId === queue.userId, `Cannot process batch ${dbBatch.batchId} from unexpected user` ); const batch = fromDbMutationBatch(this.serializer, dbBatch); return removeMutationBatch(txn, queue.userId, batch).next( () => {} ); } ); }); }); }); } /** * Ensures that every document in the remote document cache has a corresponding sentinel row * with a sequence number. Missing rows are given the most recently used sequence number. */ private ensureSequenceNumbers( txn: SimpleDbTransaction ): PersistencePromise<void> { const documentTargetStore = txn.store< DbTargetDocumentKey, DbTargetDocument >(DbTargetDocument.store); const documentsStore = txn.store<DbRemoteDocumentKey, DbRemoteDocument>( DbRemoteDocument.store ); const globalTargetStore = txn.store<DbTargetGlobalKey, DbTargetGlobal>( DbTargetGlobal.store ); return globalTargetStore.get(DbTargetGlobal.key).next(metadata => { debugAssert( !!metadata, 'Metadata should have been written during the version 3 migration' ); const writeSentinelKey = ( path: ResourcePath ): PersistencePromise<void> => { return documentTargetStore.put( new DbTargetDocument( 0, encodeResourcePath(path), metadata!.highestListenSequenceNumber! ) ); }; const promises: Array<PersistencePromise<void>> = []; return documentsStore .iterate((key, doc) => { const path = new ResourcePath(key); const docSentinelKey = sentinelKey(path); promises.push( documentTargetStore.get(docSentinelKey).next(maybeSentinel => { if (!maybeSentinel) { return writeSentinelKey(path); } else { return PersistencePromise.resolve(); } }) ); }) .next(() => PersistencePromise.waitFor(promises)); }); } private createCollectionParentIndex( db: IDBDatabase, txn: SimpleDbTransaction ): PersistencePromise<void> { // Create the index. db.createObjectStore(DbCollectionParent.store, { keyPath: DbCollectionParent.keyPath }); const collectionParentsStore = txn.store< DbCollectionParentKey, DbCollectionParent >(DbCollectionParent.store); // Helper to add an index entry iff we haven't already written it. const cache = new MemoryCollectionParentIndex(); const addEntry = ( collectionPath: ResourcePath ): PersistencePromise<void> | undefined => { if (cache.add(collectionPath)) { const collectionId = collectionPath.lastSegment(); const parentPath = collectionPath.popLast(); return collectionParentsStore.put({ collectionId, parent: encodeResourcePath(parentPath) }); } }; // Index existing remote documents. return txn .store<DbRemoteDocumentKey, DbRemoteDocument>(DbRemoteDocument.store) .iterate({ keysOnly: true }, (pathSegments, _) => { const path = new ResourcePath(pathSegments); return addEntry(path.popLast()); }) .next(() => { // Index existing mutations. return txn .store<DbDocumentMutationKey, DbDocumentMutation>( DbDocumentMutation.store ) .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => { const path = decodeResourcePath(encodedPath); return addEntry(path.popLast()); }); }); } private rewriteCanonicalIds( txn: SimpleDbTransaction ): PersistencePromise<void> { const targetStore = txn.store<DbTargetKey, DbTarget>(DbTarget.store); return targetStore.iterate((key, originalDbTarget) => { const originalTargetData = fromDbTarget(originalDbTarget); const updatedDbTarget = toDbTarget(this.serializer, originalTargetData); return targetStore.put(updatedDbTarget); }); } } function sentinelKey(path: ResourcePath): DbTargetDocumentKey { return [0, encodeResourcePath(path)]; } function createPrimaryClientStore(db: IDBDatabase): void { db.createObjectStore(DbPrimaryClient.store); } function createMutationQueue(db: IDBDatabase): void { db.createObjectStore(DbMutationQueue.store, { keyPath: DbMutationQueue.keyPath }); const mutationBatchesStore = db.createObjectStore(DbMutationBatch.store, { keyPath: DbMutationBatch.keyPath, autoIncrement: true }); mutationBatchesStore.createIndex( DbMutationBatch.userMutationsIndex, DbMutationBatch.userMutationsKeyPath, { unique: true } ); db.createObjectStore(DbDocumentMutation.store); } /** * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads * and rewrites all data. */ function upgradeMutationBatchSchemaAndMigrateData( db: IDBDatabase, txn: SimpleDbTransaction ): PersistencePromise<void> { const v1MutationsStore = txn.store<[string, number], DbMutationBatch>( DbMutationBatch.store ); return v1MutationsStore.loadAll().next(existingMutations => { db.deleteObjectStore(DbMutationBatch.store); const mutationsStore = db.createObjectStore(DbMutationBatch.store, { keyPath: DbMutationBatch.keyPath, autoIncrement: true }); mutationsStore.createIndex( DbMutationBatch.userMutationsIndex, DbMutationBatch.userMutationsKeyPath, { unique: true } ); const v3MutationsStore = txn.store<DbMutationBatchKey, DbMutationBatch>( DbMutationBatch.store ); const writeAll = existingMutations.map(mutation => v3MutationsStore.put(mutation) ); return PersistencePromise.waitFor(writeAll); }); } function createRemoteDocumentCache(db: IDBDatabase): void { db.createObjectStore(DbRemoteDocument.store); } function createDocumentGlobalStore(db: IDBDatabase): void { db.createObjectStore(DbRemoteDocumentGlobal.store); } function createQueryCache(db: IDBDatabase): void { const targetDocumentsStore = db.createObjectStore(DbTargetDocument.store, { keyPath: DbTargetDocument.keyPath }); targetDocumentsStore.createIndex( DbTargetDocument.documentTargetsIndex, DbTargetDocument.documentTargetsKeyPath, { unique: true } ); const targetStore = db.createObjectStore(DbTarget.store, { keyPath: DbTarget.keyPath }); // NOTE: This is unique only because the TargetId is the suffix. targetStore.createIndex( DbTarget.queryTargetsIndexName, DbTarget.queryTargetsKeyPath, { unique: true } ); db.createObjectStore(DbTargetGlobal.store); } function dropQueryCache(db: IDBDatabase): void { db.deleteObjectStore(DbTargetDocument.store); db.deleteObjectStore(DbTarget.store); db.deleteObjectStore(DbTargetGlobal.store); } function dropRemoteDocumentChangesStore(db: IDBDatabase): void { if (db.objectStoreNames.contains('remoteDocumentChanges')) { db.deleteObjectStore('remoteDocumentChanges'); } } /** * Creates the target global singleton row. * * @param txn - The version upgrade transaction for indexeddb */ function writeEmptyTargetGlobalEntry( txn: SimpleDbTransaction ): PersistencePromise<void> { const globalStore = txn.store<DbTargetGlobalKey, DbTargetGlobal>( DbTargetGlobal.store ); const metadata = new DbTargetGlobal( /*highestTargetId=*/ 0, /*lastListenSequenceNumber=*/ 0, SnapshotVersion.min().toTimestamp(), /*targetCount=*/ 0 ); return globalStore.put(DbTargetGlobal.key, metadata); } /** * Creates indices on the RemoteDocuments store used for both multi-tab * and Index-Free queries. */ function createRemoteDocumentReadTimeIndex(txn: IDBTransaction): void { const remoteDocumentStore = txn.objectStore(DbRemoteDocument.store); remoteDocumentStore.createIndex( DbRemoteDocument.readTimeIndex, DbRemoteDocument.readTimeIndexPath, { unique: false } ); remoteDocumentStore.createIndex( DbRemoteDocument.collectionReadTimeIndex, DbRemoteDocument.collectionReadTimeIndexPath, { unique: false } ); } function createClientMetadataStore(db: IDBDatabase): void { db.createObjectStore(DbClientMetadata.store, { keyPath: DbClientMetadata.keyPath }); } function createBundlesStore(db: IDBDatabase): void { db.createObjectStore(DbBundle.store, { keyPath: DbBundle.keyPath }); } function createNamedQueriesStore(db: IDBDatabase): void { db.createObjectStore(DbNamedQuery.store, { keyPath: DbNamedQuery.keyPath }); }
the_stack
import test, { Macro } from 'ava'; import { fc, testProp } from 'ava-fast-check'; import { bigIntToBinUint256BEClamped, bigIntToBinUint64LE, bigIntToBinUint64LEClamped, bigIntToBinUintLE, bigIntToBitcoinVarInt, binToBigIntUint256BE, binToBigIntUint64LE, binToBigIntUintBE, binToBigIntUintLE, binToHex, binToNumberInt16LE, binToNumberInt32LE, binToNumberUint16LE, binToNumberUint32LE, binToNumberUintLE, hexToBin, numberToBinInt16LE, numberToBinInt32LE, numberToBinInt32TwosCompliment, numberToBinUint16BE, numberToBinUint16LE, numberToBinUint16LEClamped, numberToBinUint32BE, numberToBinUint32LE, numberToBinUint32LEClamped, numberToBinUintLE, readBitcoinVarInt, varIntPrefixToSize, } from '../lib'; test('numberToBinUint16LE', (t) => { t.deepEqual(numberToBinUint16LE(0), Uint8Array.from([0, 0])); t.deepEqual(numberToBinUint16LE(1), Uint8Array.from([1, 0])); t.deepEqual(numberToBinUint16LE(0x1234), Uint8Array.from([0x34, 0x12])); }); test('numberToBinUint16BE', (t) => { t.deepEqual(numberToBinUint16BE(0), Uint8Array.from([0, 0])); t.deepEqual(numberToBinUint16BE(1), Uint8Array.from([0, 1])); t.deepEqual(numberToBinUint16BE(0x1234), Uint8Array.from([0x12, 0x34])); }); test('numberToBinUint16LE vs. numberToBinUint16LEClamped: behavior on overflow', (t) => { t.deepEqual( numberToBinUint16LE(0x01_0000), numberToBinUint16LE(0x01_0000 % (0xffff + 1)) ); t.deepEqual( numberToBinUint16LEClamped(0x01_0000), Uint8Array.from([0xff, 0xff]) ); }); test('numberToBinUint16LE vs. numberToBinUint16LEClamped: behavior on negative numbers', (t) => { t.deepEqual(numberToBinUint16LE(-2), numberToBinUint16LE(0xffff - 1)); t.deepEqual(numberToBinUint16LEClamped(-2), Uint8Array.from([0, 0])); }); test('numberToBinUint32LE', (t) => { t.deepEqual(numberToBinUint32LE(0), Uint8Array.from([0, 0, 0, 0])); t.deepEqual(numberToBinUint32LE(1), Uint8Array.from([1, 0, 0, 0])); t.deepEqual(numberToBinUint32LE(0x1234), Uint8Array.from([0x34, 0x12, 0, 0])); t.deepEqual( numberToBinUint32LE(0x12345678), Uint8Array.from([0x78, 0x56, 0x34, 0x12]) ); }); test('numberToBinUint32BE', (t) => { t.deepEqual(numberToBinUint32BE(0), Uint8Array.from([0, 0, 0, 0])); t.deepEqual(numberToBinUint32BE(1), Uint8Array.from([0, 0, 0, 1])); t.deepEqual(numberToBinUint32BE(0x1234), Uint8Array.from([0, 0, 0x12, 0x34])); t.deepEqual( numberToBinUint32BE(0x12345678), Uint8Array.from([0x12, 0x34, 0x56, 0x78]) ); }); test('numberToBinUint32LE vs. numberToBinUint32LEClamped: behavior on overflow', (t) => { t.deepEqual( numberToBinUint32LE(0x01_0000_0000), numberToBinUint32LE(0x01_0000_0000 % (0xffffffff + 1)) ); t.deepEqual( numberToBinUint32LEClamped(0x01_0000_0000), Uint8Array.from([0xff, 0xff, 0xff, 0xff]) ); }); test('numberToBinUint32LE: behavior on negative numbers', (t) => { t.deepEqual(numberToBinUint32LE(-2), numberToBinUint32LE(0xffffffff - 1)); t.deepEqual(numberToBinUint32LEClamped(-2), Uint8Array.from([0, 0, 0, 0])); }); test('numberToBinUintLE', (t) => { t.deepEqual( numberToBinUintLE(Number.MAX_SAFE_INTEGER), Uint8Array.from([255, 255, 255, 255, 255, 255, 31]) ); }); test('numberToBinInt16LE', (t) => { t.deepEqual(numberToBinInt16LE(0), Uint8Array.from([0, 0])); t.deepEqual(numberToBinInt16LE(1), Uint8Array.from([1, 0])); t.deepEqual(numberToBinInt16LE(0x1234), Uint8Array.from([0x34, 0x12])); t.deepEqual(numberToBinInt16LE(-0x1234), Uint8Array.from([0xcc, 0xed])); }); test('numberToBinInt32LE', (t) => { t.deepEqual(numberToBinInt32LE(0), Uint8Array.from([0, 0, 0, 0])); t.deepEqual(numberToBinInt32LE(1), Uint8Array.from([1, 0, 0, 0])); t.deepEqual(numberToBinInt32LE(0x1234), Uint8Array.from([0x34, 0x12, 0, 0])); t.deepEqual( numberToBinInt32LE(-0x1234), Uint8Array.from([0xcc, 0xed, 0xff, 0xff]) ); t.deepEqual( numberToBinUint32LE(0x12345678), Uint8Array.from([0x78, 0x56, 0x34, 0x12]) ); t.deepEqual( numberToBinInt32LE(-0x12345678), Uint8Array.from([0x88, 0xa9, 0xcb, 0xed]) ); }); test('numberToBinInt32TwosCompliment', (t) => { t.deepEqual(numberToBinInt32TwosCompliment(0), Uint8Array.from([0, 0, 0, 0])); t.deepEqual(numberToBinInt32TwosCompliment(1), Uint8Array.from([1, 0, 0, 0])); t.deepEqual( numberToBinInt32TwosCompliment(-0xffffffff), Uint8Array.from([1, 0, 0, 0]) ); t.deepEqual( numberToBinInt32TwosCompliment(0xffffffff), Uint8Array.from([255, 255, 255, 255]) ); t.deepEqual( numberToBinInt32TwosCompliment(-1), Uint8Array.from([255, 255, 255, 255]) ); t.deepEqual( numberToBinInt32TwosCompliment(0xffff), Uint8Array.from([255, 255, 0, 0]) ); t.deepEqual( numberToBinInt32TwosCompliment(-0xffff), Uint8Array.from([1, 0, 255, 255]) ); t.deepEqual( numberToBinInt32TwosCompliment(1234567890), Uint8Array.from([210, 2, 150, 73]) ); t.deepEqual( numberToBinInt32TwosCompliment(-1234567890), Uint8Array.from([46, 253, 105, 182]) ); }); test('bigIntToBinUint64LE', (t) => { t.deepEqual( bigIntToBinUint64LE(BigInt(0)), Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0]) ); t.deepEqual( bigIntToBinUint64LE(BigInt(0x01)), Uint8Array.from([0x01, 0, 0, 0, 0, 0, 0, 0]) ); t.deepEqual( bigIntToBinUint64LE(BigInt(0x12345678)), Uint8Array.from([0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0]) ); t.deepEqual( bigIntToBinUint64LE(BigInt(Number.MAX_SAFE_INTEGER)), Uint8Array.from([255, 255, 255, 255, 255, 255, 31, 0]) ); t.deepEqual( bigIntToBinUint64LE(BigInt('0xffffffffffffffff')), Uint8Array.from([255, 255, 255, 255, 255, 255, 255, 255]) ); }); test('bigIntToBinUint64LE vs. bigIntToBinUint64LEClamped: behavior on overflow', (t) => { t.deepEqual( bigIntToBinUint64LE(BigInt('0x010000000000000000')), bigIntToBinUint64LE( BigInt('0x010000000000000000') % (BigInt('0xffffffffffffffff') + BigInt(1)) ) ); t.deepEqual( bigIntToBinUint64LEClamped(BigInt('0x010000000000000000')), Uint8Array.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) ); }); test('bigIntToBinUint64LE vs. bigIntToBinUint64LEClamped: behavior on negative numbers', (t) => { t.deepEqual( bigIntToBinUint64LE(BigInt(-1)), Uint8Array.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) ); t.deepEqual( bigIntToBinUint64LEClamped(BigInt(-1)), Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0]) ); }); test('bigIntToBitcoinVarInt: larger values return modulo result after opcode', (t) => { t.deepEqual( bigIntToBitcoinVarInt(BigInt('0x010000000000000001')), Uint8Array.from([0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) ); }); test('binToNumberUintLE', (t) => { t.deepEqual(binToNumberUintLE(Uint8Array.from([0x12])), 0x12); t.deepEqual(binToNumberUintLE(Uint8Array.from([0x34, 0x12])), 0x1234); t.deepEqual( binToNumberUintLE(Uint8Array.from([0x78, 0x56, 0x34, 0x12])), 0x12345678 ); t.deepEqual( binToNumberUintLE(Uint8Array.from([0x90, 0x78, 0x56, 0x34, 0x12])), 0x1234567890 ); t.deepEqual( binToNumberUintLE(Uint8Array.from([255, 255, 255, 255, 255, 255, 31])), Number.MAX_SAFE_INTEGER ); t.deepEqual(binToNumberUintLE(Uint8Array.from([0x56, 0x34, 0x12])), 0x123456); const data = Uint8Array.from([0x90, 0x78, 0x56, 0x34, 0x12]); const view = data.subarray(2); t.deepEqual(binToNumberUintLE(view), 0x123456); t.throws(() => { binToNumberUintLE(Uint8Array.of(0x12), 2); }); }); testProp( '[fast-check] numberToBinUintLE <-> binToNumberUintLE', [fc.integer(0, Number.MAX_SAFE_INTEGER)], (t, maxSafeInt) => t.deepEqual(binToNumberUintLE(numberToBinUintLE(maxSafeInt)), maxSafeInt) ); test('binToNumberUint16LE', (t) => { t.deepEqual(binToNumberUint16LE(Uint8Array.from([0x34, 0x12])), 0x1234); const data = Uint8Array.from([0x90, 0x78, 0x56, 0x34, 0x12, 0x00]); const view = data.subarray(2, 4); t.deepEqual(binToNumberUint16LE(view), 0x3456); }); test('binToNumberInt16LE', (t) => { t.deepEqual(binToNumberInt16LE(Uint8Array.from([0x34, 0x12])), 0x1234); t.deepEqual(binToNumberInt16LE(Uint8Array.from([0xcc, 0xed])), -0x1234); }); test('binToNumberInt32LE', (t) => { t.deepEqual( binToNumberInt32LE(Uint8Array.from([0x78, 0x56, 0x34, 0x12])), 0x12345678 ); t.deepEqual( binToNumberInt32LE(Uint8Array.from([0x88, 0xa9, 0xcb, 0xed])), -0x12345678 ); }); test('binToNumberUint16LE: ignores bytes after the 2nd', (t) => { t.deepEqual( binToNumberUint16LE(Uint8Array.from([0x78, 0x56, 0x34, 0x12, 0xff])), 0x5678 ); }); test('binToNumberUint32LE', (t) => { t.deepEqual( binToNumberUint32LE(Uint8Array.from([0x78, 0x56, 0x34, 0x12])), 0x12345678 ); const data = Uint8Array.from([0x90, 0x78, 0x56, 0x34, 0x12, 0x00]); const view = data.subarray(2); t.deepEqual(binToNumberUint32LE(view), 0x123456); }); test('binToNumberUint32LE: ignores bytes after the 4th', (t) => { t.deepEqual( binToNumberUint32LE(Uint8Array.from([0x78, 0x56, 0x34, 0x12, 0xff])), 0x12345678 ); }); test('binToBigIntUintBE', (t) => { t.deepEqual(binToBigIntUintBE(Uint8Array.from([0x12])), BigInt(0x12)); t.deepEqual(binToBigIntUintBE(Uint8Array.from([0x12, 0x34])), BigInt(0x1234)); t.deepEqual( binToBigIntUintBE(Uint8Array.from([0x12, 0x34, 0x56])), BigInt(0x123456) ); t.deepEqual( binToBigIntUintBE(Uint8Array.from([0x12, 0x34, 0x56, 0x78])), BigInt(0x12345678) ); t.deepEqual( binToBigIntUintBE(Uint8Array.from([0x12, 0x34, 0x56, 0x78, 0x90])), BigInt(0x1234567890) ); t.deepEqual( binToBigIntUintBE( Uint8Array.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]) ), BigInt('0x1234567890abcdef') ); t.deepEqual( binToBigIntUintBE(Uint8Array.from([0x56, 0x78, 0x90, 0xab, 0xcd, 0xef])), BigInt('0x567890abcdef') ); const d = Uint8Array.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]); const view = d.subarray(2); t.deepEqual(binToBigIntUintBE(view), BigInt('0x567890abcdef')); t.throws(() => { binToBigIntUintBE(Uint8Array.of(0x12), 2); }); }); test('binToBigIntUint256BE and bigIntToBinUint256BEClamped', (t) => { t.deepEqual(binToBigIntUint256BE(new Uint8Array(32)), BigInt(0)); t.deepEqual(bigIntToBinUint256BEClamped(BigInt(0)), new Uint8Array(32)); t.deepEqual(bigIntToBinUint256BEClamped(BigInt(-1)), new Uint8Array(32)); const secp256k1OrderNHex = 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'; const secp256k1OrderNBin = hexToBin(secp256k1OrderNHex); const secp256k1OrderN = BigInt(`0x${secp256k1OrderNHex}`); t.deepEqual(binToBigIntUint256BE(secp256k1OrderNBin), secp256k1OrderN); t.deepEqual(bigIntToBinUint256BEClamped(secp256k1OrderN), secp256k1OrderNBin); const max = new Uint8Array(32); max.fill(255); const overMax = new Uint8Array(33); // eslint-disable-next-line functional/immutable-data overMax[0] = 255; t.deepEqual( bigIntToBinUint256BEClamped(BigInt(`0x${binToHex(overMax)}`)), max ); }); testProp( '[fast-check] binToBigIntUint256BE <-> bigIntToBinUint256BEClamped', [fc.bigUintN(256)], (t, uint256) => t.deepEqual( binToBigIntUint256BE(bigIntToBinUint256BEClamped(uint256)), uint256 ) ); test('binToBigIntUintLE', (t) => { t.deepEqual(binToBigIntUintLE(Uint8Array.from([0x12])), BigInt(0x12)); t.deepEqual(binToBigIntUintLE(Uint8Array.from([0x34, 0x12])), BigInt(0x1234)); t.deepEqual( binToBigIntUintLE(Uint8Array.from([0x56, 0x34, 0x12])), BigInt(0x123456) ); t.deepEqual( binToBigIntUintLE(Uint8Array.from([0x78, 0x56, 0x34, 0x12])), BigInt(0x12345678) ); t.deepEqual( binToBigIntUintLE(Uint8Array.from([0x90, 0x78, 0x56, 0x34, 0x12])), BigInt(0x1234567890) ); t.deepEqual( binToBigIntUintLE( Uint8Array.from([0xef, 0xcd, 0xab, 0x90, 0x78, 0x56, 0x34, 0x12]) ), BigInt('0x1234567890abcdef') ); t.deepEqual( binToBigIntUintLE(Uint8Array.from([0xab, 0x90, 0x78, 0x56, 0x34, 0x12])), BigInt('0x1234567890ab') ); const d = Uint8Array.from([0xef, 0xcd, 0xab, 0x90, 0x78, 0x56, 0x34, 0x12]); const view = d.subarray(2); t.deepEqual(binToBigIntUintLE(view), BigInt('0x1234567890ab')); t.throws(() => { binToBigIntUintLE(Uint8Array.of(0x12), 2); }); }); testProp( '[fast-check] bigIntToBinUintLE <-> binToBigIntUintBE -> reverse', [fc.bigUintN(256)], (t, uint256) => { const bin = bigIntToBinUintLE(uint256); const binReverse = bin.slice().reverse(); t.deepEqual(binToBigIntUintBE(binReverse), binToBigIntUintLE(bin)); } ); testProp( '[fast-check] bigIntToBinUintLE <-> binToBigIntUintLE', [fc.bigUintN(65)], (t, uint65) => t.deepEqual(binToBigIntUintLE(bigIntToBinUintLE(uint65)), uint65) ); test('binToBigIntUint64LE', (t) => { t.deepEqual( binToBigIntUint64LE(Uint8Array.from([0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0])), BigInt(0x12345678) ); t.deepEqual( binToBigIntUint64LE( Uint8Array.from([0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01]) ), BigInt('0x0123456789abcdef') ); t.deepEqual( binToBigIntUint64LE( Uint8Array.from([ 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, 0x00, 0x00, ]) ), BigInt('0x0123456789abcdef') ); const data = Uint8Array.from([0x90, 0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0, 0]); const view = data.subarray(2); t.deepEqual(binToBigIntUint64LE(view), BigInt(0x123456)); t.throws(() => binToBigIntUint64LE(Uint8Array.from([0x78, 0x56, 0x34, 0x12])) ); }); test('readBitcoinVarInt: offset is optional', (t) => { t.deepEqual(readBitcoinVarInt(hexToBin('00')), { nextOffset: 1, value: BigInt(0x00), }); }); const varIntVector: Macro<[string, bigint, number, number?, string?]> = ( t, hex, value, nextOffset, start = 0, expected = hex // eslint-disable-next-line max-params ) => { t.deepEqual(readBitcoinVarInt(hexToBin(hex), start), { nextOffset, value, }); t.deepEqual(bigIntToBitcoinVarInt(value), hexToBin(expected)); }; // eslint-disable-next-line functional/immutable-data varIntVector.title = (_, string) => `readBitcoinVarInt/bigIntToBitcoinVarInt: ${string}`; test(varIntVector, '00', BigInt(0x00), 1); test(varIntVector, '01', BigInt(0x01), 1); test(varIntVector, '12', BigInt(0x12), 1); test(varIntVector, '6a', BigInt(0x6a), 1); test(varIntVector, '00006a', BigInt(0x6a), 3, 2, '6a'); test(varIntVector, 'fc', BigInt(0xfc), 1); test(varIntVector, 'fdfd00', BigInt(0x00fd), 3); test(varIntVector, '000000fdfd00', BigInt(0xfd), 6, 3, 'fdfd00'); test(varIntVector, 'fdfe00', BigInt(0x00fe), 3); test(varIntVector, 'fdff00', BigInt(0x00ff), 3); test(varIntVector, 'fd1111', BigInt(0x1111), 3); test(varIntVector, 'fd1234', BigInt(0x3412), 3); test(varIntVector, 'fdfeff', BigInt(0xfffe), 3); test(varIntVector, 'fdffff', BigInt(0xffff), 3); test(varIntVector, 'fe00000100', BigInt(0x010000), 5); test(varIntVector, '00fe00000100', BigInt(0x010000), 6, 1, 'fe00000100'); test(varIntVector, 'fe01000100', BigInt(0x010001), 5); test(varIntVector, 'fe11111111', BigInt(0x11111111), 5); test(varIntVector, 'fe12345678', BigInt(0x78563412), 5); test(varIntVector, 'feffffffff', BigInt(0xffffffff), 5); test(varIntVector, 'ff0000000001000000', BigInt(0x0100000000), 9); test( varIntVector, '0000ff0000000001000000', BigInt(0x0100000000), 11, 2, 'ff0000000001000000' ); test(varIntVector, 'ff0100000001000000', BigInt(0x0100000001), 9); test(varIntVector, 'ff1111111111111111', BigInt('0x1111111111111111'), 9); test(varIntVector, 'ff1234567890abcdef', BigInt('0xefcdab9078563412'), 9); testProp( '[fast-check] bigIntToBitcoinVarInt <-> readBitcoinVarInt', [fc.bigUintN(64)], (t, uint64) => { const varInt = bigIntToBitcoinVarInt(uint64); const expectedOffset = varIntPrefixToSize(varInt[0]); const result = readBitcoinVarInt(varInt); t.deepEqual(result, { nextOffset: expectedOffset, value: uint64 }); } );
the_stack
'use strict' import { Address as AddressType } from './types/Address' import { ArrayType } from './types/ArrayType' import { Bool as BoolType } from './types/Bool' import { DynamicByteArray as BytesType } from './types/DynamicByteArray' import { FixedByteArray as BytesXType } from './types/FixedByteArray' import { Enum as EnumType } from './types/Enum' import { StringType } from './types/StringType' import { Struct as StructType } from './types/Struct' import { Int as IntType } from './types/Int' import { Uint as UintType } from './types/Uint' import { Mapping as MappingType } from './types/Mapping' import { extractLocation, removeLocation } from './types/util' /** * mapping decode the given @arg type * * @param {String} type - type given by the AST * @return {Object} returns decoded info about the current type: { storageBytes, typeName} */ function mapping (type, stateDefinitions, contractName) { const match = type.match(/mapping\((.*?)=>(.*)\)$/) const keyTypeName = match[1].trim() const valueTypeName = match[2].trim() const keyType = parseType(keyTypeName, stateDefinitions, contractName, 'storage') const valueType = parseType(valueTypeName, stateDefinitions, contractName, 'storage') var underlyingTypes = { keyType: keyType, valueType: valueType } return new MappingType(underlyingTypes, 'location', removeLocation(type)) } /** * Uint decode the given @arg type * * @param {String} type - type given by the AST (e.g uint256, uint32) * @return {Object} returns decoded info about the current type: { storageBytes, typeName} */ function uint (type) { type = type === 'uint' ? 'uint256' : type const storageBytes = parseInt(type.replace('uint', '')) / 8 return new UintType(storageBytes) } /** * Int decode the given @arg type * * @param {String} type - type given by the AST (e.g int256, int32) * @return {Object} returns decoded info about the current type: { storageBytes, typeName} */ function int (type) { type = type === 'int' ? 'int256' : type const storageBytes = parseInt(type.replace('int', '')) / 8 return new IntType(storageBytes) } /** * Address decode the given @arg type * * @param {String} type - type given by the AST (e.g address) * @return {Object} returns decoded info about the current type: { storageBytes, typeName} */ function address (type) { return new AddressType() } /** * Bool decode the given @arg type * * @param {String} type - type given by the AST (e.g bool) * @return {Object} returns decoded info about the current type: { storageBytes, typeName} */ function bool (type) { return new BoolType() } /** * DynamicByteArray decode the given @arg type * * @param {String} type - type given by the AST (e.g bytes storage ref) * @param {null} stateDefinitions - all state definitions given by the AST (including struct and enum type declaration) for all contracts * @param {null} contractName - contract the @args typeName belongs to * @param {String} location - location of the data (storage ref| storage pointer| memory| calldata) * @return {Object} returns decoded info about the current type: { storageBytes, typeName} */ function dynamicByteArray (type, stateDefinitions, contractName, location) { if (!location) { location = extractLocation(type) } if (location) { return new BytesType(location) } else { return null } } /** * FixedByteArray decode the given @arg type * * @param {String} type - type given by the AST (e.g bytes16) * @return {Object} returns decoded info about the current type: { storageBytes, typeName} */ function fixedByteArray (type) { const storageBytes = parseInt(type.replace('bytes', '')) return new BytesXType(storageBytes) } /** * StringType decode the given @arg type * * @param {String} type - type given by the AST (e.g string storage ref) * @param {null} stateDefinitions - all state definitions given by the AST (including struct and enum type declaration) for all contracts * @param {null} contractName - contract the @args typeName belongs to * @param {String} location - location of the data (storage ref| storage pointer| memory| calldata) * @return {Object} returns decoded info about the current type: { storageBytes, typeName} */ function stringType (type, stateDefinitions, contractName, location) { if (!location) { location = extractLocation(type) } if (location) { return new StringType(location) } else { return null } } /** * ArrayType decode the given @arg type * * @param {String} type - type given by the AST (e.g int256[] storage ref, int256[] storage ref[] storage ref) * @param {Object} stateDefinitions - all state definitions given by the AST (including struct and enum type declaration) for all contracts * @param {String} contractName - contract the @args typeName belongs to * @param {String} location - location of the data (storage ref| storage pointer| memory| calldata) * @return {Object} returns decoded info about the current type: { storageBytes, typeName, arraySize, subArray} */ function array (type, stateDefinitions, contractName, location) { const match = type.match(/(.*)\[(.*?)\]( storage ref| storage pointer| memory| calldata)?$/) if (!match) { console.log('unable to parse type ' + type) return null } if (!location) { location = match[3].trim() } const arraySize = match[2] === '' ? 'dynamic' : parseInt(match[2]) const underlyingType = parseType(match[1], stateDefinitions, contractName, location) if (underlyingType === null) { console.log('unable to parse type ' + type) return null } return new ArrayType(underlyingType, arraySize, location) } /** * Enum decode the given @arg type * * @param {String} type - type given by the AST (e.g enum enumDef) * @param {Object} stateDefinitions - all state definitions given by the AST (including struct and enum type declaration) for all contracts * @param {String} contractName - contract the @args typeName belongs to * @return {Object} returns decoded info about the current type: { storageBytes, typeName, enum} */ function enumType (type, stateDefinitions, contractName) { const match = type.match(/enum (.*)/) const enumDef = getEnum(match[1], stateDefinitions, contractName) if (enumDef === null) { console.log('unable to retrieve decode info of ' + type) return null } return new EnumType(enumDef) } /** * Struct decode the given @arg type * * @param {String} type - type given by the AST (e.g struct structDef storage ref) * @param {Object} stateDefinitions - all state definitions given by the AST (including struct and enum type declaration) for all contracts * @param {String} contractName - contract the @args typeName belongs to * @param {String} location - location of the data (storage ref| storage pointer| memory| calldata) * @return {Object} returns decoded info about the current type: { storageBytes, typeName, members} */ function struct (type, stateDefinitions, contractName, location) { const match = type.match(/struct (\S*?)( storage ref| storage pointer| memory| calldata)?$/) if (match) { if (!location) { location = match[2].trim() } const memberDetails = getStructMembers(match[1], stateDefinitions, contractName, location) // type is used to extract the ast struct definition if (!memberDetails) return null return new StructType(memberDetails, location, match[1]) } else { return null } } /** * retrieve enum declaration of the given @arg type * * @param {String} type - type given by the AST (e.g enum enumDef) * @param {Object} stateDefinitions - all state declarations given by the AST (including struct and enum type declaration) for all contracts * @param {String} contractName - contract the @args typeName belongs to * @return {Array} - containing all value declaration of the current enum type */ function getEnum (type, stateDefinitions, contractName) { const split = type.split('.') if (!split.length) { type = contractName + '.' + type } else { contractName = split[0] } const state = stateDefinitions[contractName] if (state) { for (const dec of state.stateDefinitions) { if (dec && dec.name && type === contractName + '.' + dec.name) { return dec } } } return null } /** * retrieve memebers declared in the given @arg tye * * @param {String} typeName - name of the struct type (e.g struct <name>) * @param {Object} stateDefinitions - all state definition given by the AST (including struct and enum type declaration) for all contracts * @param {String} contractName - contract the @args typeName belongs to * @param {String} location - location of the data (storage ref| storage pointer| memory| calldata) * @return {Array} containing all members of the current struct type */ function getStructMembers (type, stateDefinitions, contractName, location) { if (type.indexOf('.') === -1) { type = contractName + '.' + type } if (!contractName) { contractName = type.split('.')[0] } const state = stateDefinitions[contractName] if (state) { for (const dec of state.stateDefinitions) { if (dec.nodeType === 'StructDefinition' && type === contractName + '.' + dec.name) { const offsets = computeOffsets(dec.members, stateDefinitions, contractName, location) if (!offsets) { return null } return { members: offsets.typesOffsets, storageSlots: offsets.endLocation.slot } } } } return null } /** * parse the full type * * @param {String} fullType - type given by the AST (ex: uint[2] storage ref[2]) * @return {String} returns the token type (used to instanciate the right decoder) (uint[2] storage ref[2] will return 'array', uint256 will return uintX) */ function typeClass (fullType) { fullType = removeLocation(fullType) if (fullType.lastIndexOf(']') === fullType.length - 1) { return 'array' } if (fullType.indexOf('mapping') === 0) { return 'mapping' } if (fullType.indexOf(' ') !== -1) { fullType = fullType.split(' ')[0] } const char = fullType.indexOf('bytes') === 0 ? 'X' : '' return fullType.replace(/[0-9]+/g, char) } /** * parse the type and return an object representing the type * * @param {Object} type - type name given by the ast node * @param {Object} stateDefinitions - all state stateDefinitions given by the AST (including struct and enum type declaration) for all contracts * @param {String} contractName - contract the @args typeName belongs to * @param {String} location - location of the data (storage ref| storage pointer| memory| calldata) * @return {Object} - return the corresponding decoder or null on error */ function parseType (type, stateDefinitions, contractName, location) { const decodeInfos = { contract: address, address: address, array: array, bool: bool, bytes: dynamicByteArray, bytesX: fixedByteArray, enum: enumType, string: stringType, struct: struct, int: int, uint: uint, mapping: mapping } const currentType = typeClass(type) if (currentType === null) { console.log('unable to retrieve decode info of ' + type) return null } if (decodeInfos[currentType]) { return decodeInfos[currentType](type, stateDefinitions, contractName, location) } else { return null } } /** * compute offset (slot offset and byte offset of the @arg list of types) * * @param {Array} types - list of types * @param {Object} stateDefinitions - all state definitions given by the AST (including struct and enum type declaration) for all contracts * @param {String} contractName - contract the @args typeName belongs to * @param {String} location - location of the data (storage ref| storage pointer| memory| calldata) * @return {Array} - return an array of types item: {name, type, location}. location defines the byte offset and slot offset */ function computeOffsets (types, stateDefinitions, contractName, location) { const ret = [] const storagelocation = { offset: 0, slot: 0 } for (var i in types) { var variable = types[i] var type = parseType(variable.typeDescriptions.typeString, stateDefinitions, contractName, location) if (!type) { console.log('unable to retrieve decode info of ' + variable.typeDescriptions.typeString) return null } const immutable = variable.mutability === 'immutable' const hasStorageSlots = !immutable && !variable.constant if (hasStorageSlots && storagelocation.offset + type.storageBytes > 32) { storagelocation.slot++ storagelocation.offset = 0 } ret.push({ name: variable.name, type: type, constant: variable.constant, immutable, storagelocation: { offset: !hasStorageSlots ? 0 : storagelocation.offset, slot: !hasStorageSlots ? 0 : storagelocation.slot } }) if (hasStorageSlots) { if (type.storageSlots === 1 && storagelocation.offset + type.storageBytes <= 32) { storagelocation.offset += type.storageBytes } else { storagelocation.slot += type.storageSlots storagelocation.offset = 0 } } } if (storagelocation.offset > 0) { storagelocation.slot++ } return { typesOffsets: ret, endLocation: storagelocation } } export { parseType, computeOffsets, uint as Uint, address as Address, bool as Bool, dynamicByteArray as DynamicByteArray, fixedByteArray as FixedByteArray, int as Int, stringType as String, array as Array, enumType as Enum, struct as Struct }
the_stack