text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import Events, { EventName, preloadEvent } from "../../common/util/Events"; import Tool from "../../common/util/Tool"; import { ANIMATOR_VERSION } from "../../constant/BaseConst"; import Condition from "../data/Condition"; import State from "../data/State"; import StateMachine from "../data/StateMachine"; import Transition from "../data/Transition"; import Editor from "../Editor"; import ParamItem from "../parameters/ParamItem"; import Line from "./Line"; import MachineLayer from "./MachineLayer"; import UnitBase from "./UnitBase"; import UnitState from "./UnitState"; import UnitStateMachine from "./UnitStateMachine"; const { ccclass, property } = cc._decorator; @ccclass export default class FsmCtr extends cc.Component { @property(MachineLayer) MachineLayer: MachineLayer = null; @property(cc.Node) Cross: cc.Node = null; /** 当前按下的鼠标按键 */ private _curMouseBtn: number = null; /** moveUnit跟随鼠标的偏移值 */ private _moveUnitOffset: cc.Vec2 = cc.v2(0, 0); /** 跟随鼠标移动的unit */ private _moveUnit: UnitBase = null; /** 当前选中的unit */ private _curUnit: UnitBase = null; /** 临时连线 */ private _tempLine: Line = null; /** 当前选中的line */ private _curLine: Line = null; /** 上一次点击到StateMachine的时间 ms */ private _lastClickTime: number = 0; protected onLoad() { this.node.on(cc.Node.EventType.MOUSE_DOWN, this.onMouseDown, this); this.node.on(cc.Node.EventType.MOUSE_UP, this.onMouseUp, this); this.node.on(cc.Node.EventType.MOUSE_ENTER, this.onMouseEnter, this); this.node.on(cc.Node.EventType.MOUSE_MOVE, this.onMouseMove, this); this.node.on(cc.Node.EventType.MOUSE_LEAVE, this.onMouseLeave, this); this.node.on(cc.Node.EventType.MOUSE_WHEEL, this.onMouseWheel, this); Events.targetOn(this); } protected onDestroy() { Events.targetOff(this); } protected lateUpdate() { if (this._moveUnit && this.MachineLayer.checkMoveUnit(this._moveUnit)) { this.Cross.active = true; } else { this.Cross.active = false; } } /** * 按下鼠标左键的处理 */ private onMouseDownLeft(worldPos: cc.Vec2, posInCurLayer: cc.Vec2) { let nextUnit = this.MachineLayer.getUnitByPos(posInCurLayer); if (nextUnit instanceof UnitState) { // 点击到AnyState删除临时连线 if (nextUnit.isAnyState) { this.deleteLine(this._tempLine); } this._curLine && this._curLine.select(false); this._curLine = null; this._moveUnitOffset = posInCurLayer.sub(nextUnit.node.position); this._moveUnit = nextUnit; if (this._curUnit !== nextUnit) { if (this._tempLine) { this._moveUnit = null; // 处理临时连线 let line = this.MachineLayer.getLineByUnit(this._curUnit, nextUnit); // 新增transition this._curUnit.addTransition(nextUnit, nextUnit.state); if (line) { // 删除临时连线 this.deleteLine(this._tempLine); } else { // 连接line this._tempLine.onInit(this._curUnit, nextUnit); // 清除 this._tempLine = null; } } else { // 选中state this._curUnit && this._curUnit.select(false); this._curUnit = nextUnit; this._curUnit.select(true); Events.emit(EventName.INSPECTOR_SHOW_UNIT, this._curUnit); } } } else if (nextUnit instanceof UnitStateMachine) { let now = Date.now(); let delt = now - this._lastClickTime; this._lastClickTime = now; if (this._curUnit === nextUnit && delt < 500) { this.setCurStateMachine(nextUnit.stateMachine); return; } this._curLine && this._curLine.select(false); this._curLine = null; this._moveUnitOffset = posInCurLayer.sub(nextUnit.node.position); this._moveUnit = nextUnit; if (this._curUnit !== nextUnit) { if (this._tempLine) { this._moveUnit = null; // 弹出选择菜单,显示状态机中所有状态 Events.emit(EventName.SHOW_LINE_TO_List, worldPos, nextUnit, this.MachineLayer.curStateMachine); } else { // 选中unit this._curUnit && this._curUnit.select(false); this._curUnit = nextUnit; this._curUnit.select(true); Events.emit(EventName.INSPECTOR_SHOW_UNIT, this._curUnit); } } } else { this._moveUnit = null; this._curUnit && this._curUnit.select(false); this._curUnit = null; let nextLine = this.MachineLayer.getLineByPos(posInCurLayer); if (nextLine) { if (this._curLine !== nextLine) { // 选中line this._curLine && this._curLine.select(false); this._curLine = nextLine; this._curLine.select(true); Events.emit(EventName.INSPECTOR_SHOW_LINE, this._curLine); } } else { this._curLine && this._curLine.select(false); this._curLine = null; Events.emit(EventName.INSPECTOR_HIDE); } // 删除临时连线 this.deleteLine(this._tempLine); } } /** * 按下鼠标右键的处理 */ private onMouseDownRight(posInCurLayer: cc.Vec2) { // 判断是否选中state let nextUnit = this.MachineLayer.getUnitByPos(posInCurLayer); if (nextUnit) { this._curLine && this._curLine.select(false); this._curLine = null; this._moveUnitOffset = posInCurLayer.sub(nextUnit.node.position); if (this._curUnit !== nextUnit) { this._curUnit && this._curUnit.select(false); this._curUnit = nextUnit; this._curUnit.select(true); Events.emit(EventName.INSPECTOR_SHOW_UNIT, this._curUnit); } } // 删除临时连线 this.deleteLine(this._tempLine); } private onMouseDown(event: cc.Event.EventMouse) { this._curMouseBtn = event.getButton(); let posInCtr: cc.Vec2 = this.node.convertToNodeSpaceAR(event.getLocation()); let posInCurLayer: cc.Vec2 = this.MachineLayer.node.convertToNodeSpaceAR(event.getLocation()); if (this._curMouseBtn === cc.Event.EventMouse.BUTTON_LEFT) { // 按下鼠标左键 this.onMouseDownLeft(event.getLocation(), posInCurLayer); } else if (this._curMouseBtn === cc.Event.EventMouse.BUTTON_RIGHT) { // 按下鼠标右键 this.onMouseDownRight(posInCurLayer); } else if (this._curMouseBtn === cc.Event.EventMouse.BUTTON_MIDDLE) { } } private onMouseUp(event: cc.Event.EventMouse) { let posInCtr: cc.Vec2 = this.node.convertToNodeSpaceAR(event.getLocation()); let posInCurLayer: cc.Vec2 = this.MachineLayer.node.convertToNodeSpaceAR(event.getLocation()); if (this._curMouseBtn === cc.Event.EventMouse.BUTTON_LEFT) { // bug: 没处理跨越多层transition if (this._moveUnit && this.MachineLayer.moveIntoStateMachine(this._moveUnit)) { this._moveUnit = null; this._curUnit = null; Events.emit(EventName.INSPECTOR_HIDE); } } else if (this._curMouseBtn === cc.Event.EventMouse.BUTTON_RIGHT) { // 松开鼠标右键 弹出右键菜单 let state = this.MachineLayer.getUnitByPos(posInCurLayer); let curState = (this._curUnit && this._curUnit === state) ? this._curUnit : null; Events.emit(EventName.SHOW_RIGHT_MENU, event.getLocation(), curState); } else if (this._curMouseBtn === cc.Event.EventMouse.BUTTON_MIDDLE) { } // 松开鼠标按键时清空 this._curMouseBtn = null; } private onMouseEnter(event: cc.Event.EventMouse) { if (event.getButton() === null) { this._curMouseBtn = null; } } private onMouseMove(event: cc.Event.EventMouse) { let posInCtr: cc.Vec2 = this.node.convertToNodeSpaceAR(event.getLocation()); let posInCurLayer: cc.Vec2 = this.MachineLayer.node.convertToNodeSpaceAR(event.getLocation()); if (event.getButton() === null) { this._curMouseBtn = null; } // 移动临时连线 if (this._curUnit && this._tempLine) { let unit = this.MachineLayer.getUnitByPos(posInCurLayer); if (unit && unit !== this._curUnit && ((unit instanceof UnitState && !unit.isAnyState) || unit instanceof UnitStateMachine)) { this._tempLine.setLine(this._curUnit.node.position, unit.node.position); } else { this._tempLine.setLine(this._curUnit.node.position, posInCurLayer); } } if (this._curMouseBtn === cc.Event.EventMouse.BUTTON_LEFT) { // 按住鼠标左键 移动选中的状态 if (this._moveUnit) { this._moveUnit.setPos(posInCurLayer.sub(this._moveUnitOffset)); this.Cross.position = posInCtr; } } else if (this._curMouseBtn === cc.Event.EventMouse.BUTTON_RIGHT) { } else if (this._curMouseBtn === cc.Event.EventMouse.BUTTON_MIDDLE) { // 按住鼠标中键 移动当前MachineLayer this.MachineLayer.setPos(this.MachineLayer.node.position.add(event.getDelta())); } } private onMouseLeave(event: cc.Event.EventMouse) { if (event.getButton() === null) { this._curMouseBtn = null; } } private onMouseWheel(event: cc.Event.EventMouse) { // 滚动鼠标滚轮 缩放当前MachineLayer this.MachineLayer.changeScale(event.getScrollY() > 0, event.getLocation()); } private setCurStateMachine(stateMachine: StateMachine) { if (this.MachineLayer.curStateMachine === stateMachine) { return; } this._lastClickTime = 0; this._moveUnit = null; this._curUnit = null; this._tempLine = null; this._curLine = null; this.MachineLayer.setCurStateMachine(stateMachine); Events.emit(EventName.INSPECTOR_HIDE); } /** * 删除line */ private deleteLine(line: Line) { if (!line) { return; } if (this._curLine === line) { this._curLine = null; } if (this._tempLine === line) { this._tempLine = null; } this.MachineLayer.deleteLine(line); } /** * 删除当前选中的line */ public deleteCurLine() { if (!this._curLine) { return; } this.deleteLine(this._curLine); Events.emit(EventName.INSPECTOR_HIDE); } /** * 删除当前选中的unit */ public deleteCurUnit() { if (!this._curUnit) { return; } if (this._curUnit instanceof UnitState) { if (this._curUnit.isAnyState) { return; } this.MachineLayer.deleteState(this._curUnit); } else if (this._curUnit instanceof UnitStateMachine) { if (this._curUnit.isUp) { return; } this.MachineLayer.deleteStateMachine(this._curUnit); } this._curUnit = null; this._moveUnit = null; this.deleteLine(this._tempLine); Events.emit(EventName.INSPECTOR_HIDE); } //#region 按钮回调 private onClickCreateState(event: cc.Event) { Events.emit(EventName.CLOSE_MENU); let menuNode: cc.Node = Editor.Inst.Menu.RightMenu; let posInCurLayer: cc.Vec2 = this.MachineLayer.node.convertToNodeSpaceAR(menuNode.parent.convertToWorldSpaceAR(menuNode.position)); this.MachineLayer.createState(posInCurLayer); } private onClickCreateSubMachine() { Events.emit(EventName.CLOSE_MENU); let menuNode: cc.Node = Editor.Inst.Menu.RightMenu; let posInCurLayer: cc.Vec2 = this.MachineLayer.node.convertToNodeSpaceAR(menuNode.parent.convertToWorldSpaceAR(menuNode.position)); this.MachineLayer.createStateMachine(posInCurLayer); } private onClickMakeTrasition() { Events.emit(EventName.CLOSE_MENU); if (!this._curUnit) { return; } this._tempLine = this.MachineLayer.createLine(); this._tempLine.setLine(this._curUnit.node.position, this._curUnit.node.position); } private onClickSetDefault() { Events.emit(EventName.CLOSE_MENU); if (!this._curUnit || !(this._curUnit instanceof UnitState) || this._curUnit.isAnyState) { return; } this.MachineLayer.setDefaultState(this._curUnit); } private onClickDeleteCurUnit() { Events.emit(EventName.CLOSE_MENU); this.deleteCurUnit(); } //#endregion //#region 事件监听 @preloadEvent(EventName.LINE_TO_MACHINE_STATE) private onEventLineToMachineState(state: State, to: UnitStateMachine) { if (!this._curUnit || !this._tempLine) { return; } this._moveUnit = null; // 处理临时连线 let line = this.MachineLayer.getLineByUnit(this._curUnit, to); // 新增transition this._curUnit.addTransition(to, state); if (line || (this._curUnit instanceof UnitState && this._curUnit.isAnyState)) { // 删除临时连线 this.deleteLine(this._tempLine); } else { // 连接line this._tempLine.onInit(this._curUnit, to); // 清除 this._tempLine = null; } } @preloadEvent(EventName.LINE_DELETE) private onEventLineDelete(line: Line) { this.deleteLine(line); } @preloadEvent(EventName.SET_CUR_STATE_MACHINE) private onEventSetCurStateMachine(stateMachine: StateMachine) { this.setCurStateMachine(stateMachine); } //#endregion //#region import and export private importTransitions(transitionsData: any[], state: State, stateMap: Map<string, State>, paramMap: Map<string, ParamItem>) { transitionsData.forEach((e) => { let toState: State = stateMap.get(e.toState); let transition: Transition = state.addTransition(toState); transition.hasExitTime = e.hasExitTime; e.conditions.forEach((cData) => { let paramItem = paramMap.get(cData.param); let condition: Condition = transition.addCondition(paramItem); condition.value = cData.value; condition.logic = cData.logic; }); }); } private importSubState(upData: any, upMachine: StateMachine, stateDataMap: Map<string, any>, stateMap: Map<string, State>, paramMap: Map<string, ParamItem>) { upData.subStates.forEach((name: string) => { let state = new State(upMachine, false); stateMap.set(name, state); let data = stateDataMap.get(name); state.setPosition(data.position[0], data.position[1]); state.name = data.state; state.motion = data.motion; state.speed = data.speed; state.multiplierParam = paramMap.get(data.multiplier) || null; state.loop = data.loop; upMachine.add(state); }); } private importSubMachine(upData: any, upMachine: StateMachine, subMachineDataMap: Map<string, any>, subMachineMap: Map<string, StateMachine>, stateDataMap: Map<string, any>, stateMap: Map<string, State>, paramMap: Map<string, ParamItem>) { upData.subStateMachines.forEach((name: string) => { let stateMachine = new StateMachine(upMachine); subMachineMap.set(name, stateMachine); let data = subMachineDataMap.get(name); stateMachine.setLayerPos(data.layerPos[0], data.layerPos[1]); stateMachine.setLayerScale(data.layerScale); stateMachine.setAnyStatePos(data.anyStatePos[0], data.anyStatePos[1]); stateMachine.name = data.name; stateMachine.setPosition(data.position[0], data.position[1]); stateMachine.setUpStateMachinePos(data.upStateMachinePos[0], data.upStateMachinePos[1]); upMachine.add(stateMachine); this.importSubState(data, stateMachine, stateDataMap, stateMap, paramMap); this.importSubMachine(data, stateMachine, subMachineDataMap, subMachineMap, stateDataMap, stateMap, paramMap); }); } private exportAllSubMachine(arr: any[], stateMachine: StateMachine) { stateMachine.subStateMachines.forEach((sub) => { let data = { layerPos: [sub.layerPos.x, sub.layerPos.y], layerScale: sub.layerScale, anyStatePos: [sub.anyStatePos.x, sub.anyStatePos.y], name: sub.name, position: [sub.position.x, sub.position.y], upStateMachine: sub.upStateMachine.name, upStateMachinePos: [sub.upStateMachinePos.x, sub.upStateMachinePos.y], subStates: [], subStateMachines: [], } sub.subStates.forEach((e) => { data.subStates.push(e.name); }); sub.subStateMachines.forEach((e) => { data.subStateMachines.push(e.name); }); arr.push(data); this.exportAllSubMachine(arr, sub); }); } private exportAllState(arr: any[], stateMachine: StateMachine, isRuntimeData: boolean = false) { stateMachine.subStates.forEach((e) => { let data = null; if (isRuntimeData) { data = { state: e.name, motion: e.motion, speed: e.speed, multiplier: e.getMultiplierName(), loop: e.loop, transitions: e.getAllTransitionData() } } else { data = { position: [e.position.x, e.position.y], upStateMachine: e.upStateMachine.name, state: e.name, motion: e.motion, speed: e.speed, multiplier: e.getMultiplierName(), loop: e.loop, transitions: e.getAllTransitionData() } } arr.push(data); }); stateMachine.subStateMachines.forEach((sub) => { this.exportAllState(arr, sub); }); } /** * 导入工程数据 */ public importProject(data: any) { let paramMap: Map<string, ParamItem> = Editor.Inst.Parameters.getParamMap(); let mainStateMachineData = data.mainStateMachine; let subStateMachinesData = data.subStateMachines; let defaultStateData: string = data.defaultState; let anyStateData = data.anyState; let statesData = data.states; let stateDataMap: Map<string, any> = new Map(); statesData.forEach((e: any) => { stateDataMap.set(e.state, e); }); let stateMap: Map<string, State> = new Map(); let subMachineDataMap: Map<string, any> = new Map(); subStateMachinesData.forEach((e: any) => { subMachineDataMap.set(e.name, e) }); let subMachineMap: Map<string, StateMachine> = new Map(); let main = this.MachineLayer.mainStateMachine; main.setLayerPos(mainStateMachineData.layerPos[0], mainStateMachineData.layerPos[1]); main.setLayerScale(mainStateMachineData.layerScale); main.setAnyStatePos(mainStateMachineData.anyStatePos[0], mainStateMachineData.anyStatePos[1]); this.importSubState(mainStateMachineData, main, stateDataMap, stateMap, paramMap); this.importSubMachine(mainStateMachineData, main, subMachineDataMap, subMachineMap, stateDataMap, stateMap, paramMap); if (stateMap.has(defaultStateData)) this.MachineLayer.defaultState = stateMap.get(defaultStateData); this.importTransitions(anyStateData.transitions, this.MachineLayer.anyState.state, stateMap, paramMap); statesData.forEach((e: any) => { let state: State = stateMap.get(e.state); if (!state) { cc.error('error'); } this.importTransitions(e.transitions, state, stateMap, paramMap); }); this.MachineLayer.setCurStateMachine(); } /** * 导入cocos animation文件 */ public importAnim(animData: any) { if (animData instanceof Array) { // 3.0 anim文件 animData.forEach((data) => { if (!data.hasOwnProperty('_name')) { return; } let x = Tool.randFloat(-this.MachineLayer.node.x - 100, -this.MachineLayer.node.x + 100); let y = Tool.randFloat(-this.MachineLayer.node.y - 100, -this.MachineLayer.node.y + 100); let unitState = this.MachineLayer.createState(cc.v2(x, y)); let state: State = unitState.state; state.name = data._name; state.motion = data._name; state.speed = data.speed; state.loop = data.wrapMode === cc.WrapMode.Loop; }); } else { // 2.x anim文件 let x = Tool.randFloat(-this.MachineLayer.node.x - 100, -this.MachineLayer.node.x + 100); let y = Tool.randFloat(-this.MachineLayer.node.y - 100, -this.MachineLayer.node.y + 100); let unitState = this.MachineLayer.createState(cc.v2(x, y)); let state: State = unitState.state; state.name = animData._name; state.motion = animData._name; state.speed = animData.speed; state.loop = animData.wrapMode === cc.WrapMode.Loop; } } /** * 导入spine json文件 */ public improtSpine(spineData: any) { for (let name in spineData.animations) { let x = Tool.randFloat(-this.MachineLayer.node.x - 100, -this.MachineLayer.node.x + 100); let y = Tool.randFloat(-this.MachineLayer.node.y - 100, -this.MachineLayer.node.y + 100); let unitState = this.MachineLayer.createState(cc.v2(x, y)); let state: State = unitState.state; state.name = name; state.motion = name; } } /** * 导入dragonbones json文件 */ public importDragonBones(data: any) { data.armature.forEach((e) => { e.animation.forEach((anim) => { let x = Tool.randFloat(-this.MachineLayer.node.x - 100, -this.MachineLayer.node.x + 100); let y = Tool.randFloat(-this.MachineLayer.node.y - 100, -this.MachineLayer.node.y + 100); let unitState = this.MachineLayer.createState(cc.v2(x, y)); let state: State = unitState.state; state.name = anim.name; state.motion = anim.name; state.loop = anim.playTimes === 0; }); }); } /** * 导出工程数据 */ public exportProject() { let main = this.MachineLayer.mainStateMachine; let animator = ANIMATOR_VERSION; let mainStateMachine = { layerPos: [main.layerPos.x, main.layerPos.y], layerScale: main.layerScale, anyStatePos: [main.anyStatePos.x, main.anyStatePos.y], subStates: [], subStateMachines: [], }; main.subStates.forEach((e) => { mainStateMachine.subStates.push(e.name); }); main.subStateMachines.forEach((e) => { mainStateMachine.subStateMachines.push(e.name); }); let subStateMachines = []; this.exportAllSubMachine(subStateMachines, main); let defaultState: string = this.MachineLayer.defaultState ? this.MachineLayer.defaultState.name : ''; let anyState = { transitions: this.MachineLayer.anyState.state.getAllTransitionData() }; let states = []; this.exportAllState(states, main); return { animator: animator, mainStateMachine: mainStateMachine, subStateMachines: subStateMachines, defaultState: defaultState, anyState: anyState, states: states }; } /** * 导出runtime数据 */ public exportRuntimeData() { let main = this.MachineLayer.mainStateMachine; let defaultState: string = this.MachineLayer.defaultState ? this.MachineLayer.defaultState.name : ''; let anyState = { transitions: this.MachineLayer.anyState.state.getAllTransitionData() }; let states = []; this.exportAllState(states, main, true); return { defaultState: defaultState, anyState: anyState, states: states }; } //#endregion }
the_stack
import * as fs from "fs"; import * as os from "os"; import * as path from "path"; import { prompt, out } from "../../util/interaction"; import { help, CommandArgs, AppCommand, CommandResult } from "../../util/commandline"; import { Messages } from "./lib/help-messages"; import { AppCenterClient, clientCall, models } from "../../util/apis"; import { DeviceSet, DeviceConfiguration, AppResponse } from "../../util/apis/generated/models"; import { DeviceConfigurationSort } from "./lib/deviceConfigurationSort"; import RunEspressoWizardTestCommand from "./lib/wizard/espresso"; import RunAppiumWizardTestCommand from "./lib/wizard/appium"; import RunUitestWizardTestCommand from "./lib/wizard/uitest"; import RunXCUIWizardTestCommand from "./lib/wizard/xcuitest"; import { fileExistsSync } from "../../util/misc"; import { DefaultApp, toDefaultApp } from "../../util/profile"; enum TestFramework { "Espresso" = 1, "Appium" = 2, "XCUITest" = 3, "Xamarin.UITest" = 4, "Calabash" = 5, "Manifest" = 6, } interface AppFile { name: string; // To be displayed to user. path: string; // Full path. } @help(Messages.TestCloud.Commands.Wizard) export default class WizardTestCommand extends AppCommand { private interactiveArgs: string[] = []; private _args: CommandArgs; private isAndroidApp: boolean; private _selectedApp: DefaultApp = null; constructor(args: CommandArgs) { super(args); this._args = args; } private async selectApp(client: AppCenterClient): Promise<DefaultApp> { if (!this._selectedApp) { try { this._selectedApp = super.app; } catch (e) { // no app was provided/found, so we will prompt the user this._selectedApp = await this.getApps(client); this.interactiveArgs.push("--app", this._selectedApp.identifier); } } return this._selectedApp; } public async run(client: AppCenterClient, portalBaseUrl: string): Promise<CommandResult> { const app = await this.selectApp(client); const getDeviceSets: Promise<DeviceSet[]> = client.test.listDeviceSetsOfOwner(app.ownerName, app.appName); const getAppOS: Promise<AppResponse> = client.appsOperations.get(app.ownerName, app.appName); this.isAndroidApp = (await getAppOS).os.toLowerCase() === "android"; const frameworkName: TestFramework = await this.promptFramework(); const searchApps: Promise<AppFile[]> = this.scanFolder(); const devices: string = await this.promptDevices(await getDeviceSets, app, client); this.interactiveArgs.push("--devices", devices); const async: boolean = await this.isAsync(); if (async) { this.interactiveArgs.push("--async"); } const listOfAppFiles: AppFile[] = await searchApps; const appPath: string = await this.promptAppFile(listOfAppFiles); this.interactiveArgs.push("--app-path", appPath); switch (frameworkName) { case TestFramework.Espresso: { const testApkPath: string = await this.promptAppFile(listOfAppFiles, true); this.interactiveArgs.push("--test-apk-path", testApkPath); return new RunEspressoWizardTestCommand(this._args, this.interactiveArgs).run(client, portalBaseUrl); } case TestFramework.XCUITest: { const testIpaPath: string = await this.promptAppFile(listOfAppFiles, true); this.interactiveArgs.push("--test-ipa-path", testIpaPath); return new RunXCUIWizardTestCommand(this._args, this.interactiveArgs).run(client, portalBaseUrl); } case TestFramework.Appium: { return new RunAppiumWizardTestCommand(this._args, this.interactiveArgs).run(client, portalBaseUrl); } case TestFramework["Xamarin.UITest"]: { return new RunUitestWizardTestCommand(this._args, this.interactiveArgs).run(client, portalBaseUrl); } case TestFramework.Calabash: { this.printCalabashHelp(); return { succeeded: true }; } case TestFramework.Manifest: { this.printManifestHelp(); return { succeeded: true }; } default: throw new Error("Unknown framework name!"); } } private async promptFramework(): Promise<TestFramework> { const choices = Object.keys(TestFramework) .filter((framework) => { if (this.isAndroidApp && framework === "XCUITest") { return false; } if (!this.isAndroidApp && framework === "Espresso") { return false; } return typeof TestFramework[framework as any] === "number"; }) .map((framework) => { return { name: framework, value: TestFramework[framework as any], }; }); const questions = [ { type: "list", name: "framework", message: "Pick a test framework", choices: choices, }, ]; const answers: any = await prompt.question(questions); return answers.framework; } private async promptAppFile(listOfAppFiles: AppFile[], forTest: boolean = false): Promise<string> { if (listOfAppFiles.length === 0) { return await prompt( `We could not find any app files inside the current folder. Please provide the path to the ${forTest ? "test app" : "app"}.` ); } const choices = listOfAppFiles.map((appName) => { return { name: appName.name, value: appName.path, }; }); choices.push({ name: "Enter path manually", value: "manual", }); const questions = [ { type: "list", name: "appPath", message: forTest ? "Pick a test app" : "Pick an app", choices: choices, }, ]; const answers: any = await prompt.question(questions); if (answers.appPath === "manual") { let pathIsValid: boolean; let filePath: string; while (!pathIsValid) { filePath = await prompt(`Please provide the path to the ${forTest ? "test app" : "app"}.`); if (filePath.length === 0) { pathIsValid = false; } else { pathIsValid = fileExistsSync(path.resolve(filePath)); } } return filePath; } return answers.appPath; } private async isAsync(): Promise<boolean> { const questions = [ { type: "list", name: "isAsync", message: "Should tests run in async mode?", choices: [ { name: "Yes", value: "true", }, { name: "No", value: "false", }, ], }, ]; const answers: any = await prompt.question(questions); return answers.isAsync === "true" ? true : false; } private sortDeviceSets(a: DeviceSet, b: DeviceSet): number { if (a.name > b.name) { return 1; } if (a.name < b.name) { return -1; } return 0; } private async getDevices(client: AppCenterClient, app: DefaultApp): Promise<DeviceConfiguration[]> { const configs: DeviceConfiguration[] = await client.test.getDeviceConfigurations(app.ownerName, app.appName); // Sort devices list like it is done on AppCenter Portal return configs.sort(DeviceConfigurationSort.compare); } private async getApps(client: AppCenterClient): Promise<DefaultApp> { const apps = await out.progress( "Getting list of apps...", clientCall<models.AppResponse[]>((cb) => client.appsOperations.list(cb)) ); const choices = apps.map((app: models.AppResponse) => { return { name: app.name, value: `${app.owner.name}/${app.name}`, }; }); const question = [ { type: "list", name: "app", message: "Pick an app to use", choices: choices, }, ]; const answer: any = await prompt.question(question); return toDefaultApp(answer.app); } private async promptDevices(deviceSets: DeviceSet[], app: DefaultApp, client: AppCenterClient): Promise<string> { let choices; const noDeviceSets: boolean = deviceSets.length === 0; if (noDeviceSets) { const devices = await out.progress("Getting list of devices...", this.getDevices(client, app)); choices = devices.map((config: DeviceConfiguration) => { return { name: config.name, value: config.id, }; }); } else { deviceSets = deviceSets.sort(this.sortDeviceSets); choices = deviceSets.map((config: DeviceSet) => { return { name: config.name, value: config.slug, }; }); choices.push({ name: "I want to use a single device", value: "manual", }); } const questions = [ { type: "list", name: "deviceSlug", message: noDeviceSets ? "Pick a device to use" : "Pick a device set to use", choices: choices, }, ]; const answers: any = await prompt.question(questions); let deviceId: string; if (noDeviceSets) { const deviceSelection: any = await client.test.createDeviceSelection(app.ownerName, app.appName, [answers.deviceSlug]); deviceId = deviceSelection.shortId; } else { if (answers.deviceSlug === "manual") { return await this.promptDevices([], app, client); } else { deviceId = `${app.ownerName}/${answers.deviceSlug}`; } } return deviceId; } private async scanFolder(): Promise<AppFile[]> { const appNames: AppFile[] = []; this.scanRecurse(process.cwd(), appNames); return appNames; } private scanRecurse(dirname: string, appNames: AppFile[]) { const dirContent = fs.readdirSync(dirname); for (const dir of dirContent) { const fullDir = path.join(dirname, dir); if (fs.lstatSync(fullDir).isDirectory()) { if (dir !== "node_modules") { this.scanRecurse(fullDir, appNames); } } else { if (this.isApplicationFile(dir)) { const foundApp = { name: path.relative(process.cwd(), fullDir), path: fullDir, }; if (!appNames) { appNames = [foundApp]; } else { appNames.push(foundApp); } } } } } private isApplicationFile(file: string): boolean { const fileExtension: string = path.parse(file).ext; return (this.isAndroidApp && fileExtension === ".apk") || (!this.isAndroidApp && fileExtension === ".ipa"); } private printCalabashHelp() { out.text( os.EOL + `Interactive mode is not supported. Usage: appcenter test run calabash ${this.interactiveArgs.join(" ")}` + os.EOL + os.EOL + "Additional parameters: " + os.EOL + `--project-dir: ${Messages.TestCloud.Arguments.CalabashProjectDir}` + os.EOL + `--sign-info: ${Messages.TestCloud.Arguments.CalabashSignInfo}` + os.EOL + `--config-path: ${Messages.TestCloud.Arguments.CalabashConfigPath}` + os.EOL + `--profile: ${Messages.TestCloud.Arguments.CalabashProfile}` + os.EOL + `--skip-config-check: ${Messages.TestCloud.Arguments.CalabashSkipConfigCheck}` ); } private printManifestHelp() { out.text( os.EOL + `Interactive mode is not supported. Usage: appcenter test run manifest ${this.interactiveArgs.join(" ")}` + os.EOL + os.EOL + "Additional parameters: " + os.EOL + `--manifest-path: Path to manifest file` + os.EOL + `--merged-file-name: ${Messages.TestCloud.Arguments.MergedFileName}` ); } }
the_stack
import ACLServiceAccountActions from "../../actions/ACLServiceAccountActions"; import ServiceAccount from "../../structs/ServiceAccount"; import ServiceAccountList from "../../structs/ServiceAccountList"; import * as EventTypes from "../../constants/EventTypes"; import PluginSDK from "PluginSDK"; const SDK = PluginSDK.__getSDK("organization", { enabled: true }); require("../../../../SDK").setSDK(SDK); const getACLServiceAccountsStore = require("../ACLServiceAccountsStore") .default; import * as ActionTypes from "../../constants/ActionTypes"; const OrganizationReducer = require("../../../../Reducer"); const ACLServiceAccountsStore = getACLServiceAccountsStore(); PluginSDK.__addReducer("organization", OrganizationReducer); let thisFetchAll; describe("ACLServiceAccountsStore", () => { beforeEach(() => { const serviceAccounts = []; const serviceAccountsDetails = {}; const serviceAccountsFetching = {}; // Reset state.serviceAccounts SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNTS_CHANGE, serviceAccounts, }); // Reset state.serviceAccountsDetail SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNT_SET_SERVICE_ACCOUNT, serviceAccounts: serviceAccountsDetails, }); // Reset state.serviceAccountsFetching SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNT_DETAILS_FETCH_START, serviceAccountsFetching, }); }); describe("#getServiceAccounts", () => { it("returns the serviceAccounts", () => { const serviceAccounts = [{ bar: "baz" }, { baz: "bar" }]; SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNTS_CHANGE, serviceAccounts, }); expect( ACLServiceAccountsStore.getServiceAccounts() instanceof ServiceAccountList ).toBe(true); expect( ACLServiceAccountsStore.getServiceAccounts().getItems()[0].get() ).toEqual(serviceAccounts[0]); }); }); describe("#getServiceAccountsDetail", () => { it("returns the serviceAccountsDetail", () => { const serviceAccounts = { foo: { bar: "baz", }, foobar: { baz: "bar", }, }; SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNT_SET_SERVICE_ACCOUNT, serviceAccounts, }); expect(ACLServiceAccountsStore.getServiceAccountsDetail()).toEqual( serviceAccounts ); }); }); describe("#getServiceAccountsFetching", () => { it("returns the serviceAccountsDetail", () => { const serviceAccountsFetching = { foo: { groups: true, permissions: true, serviceAccount: true, }, }; SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNT_DETAILS_FETCH_START, serviceAccountsFetching, }); expect(ACLServiceAccountsStore.getServiceAccountsFetching()).toEqual( serviceAccountsFetching ); }); }); describe("#getServiceAccountRaw", () => { it("returns {} if ServiceAccount does not exist", () => { const serviceAccounts = { foo: { bar: "baz", }, }; SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNT_SET_SERVICE_ACCOUNT, serviceAccounts, }); expect(ACLServiceAccountsStore.getServiceAccountRaw("foobar")).toEqual( {} ); }); it("returns the serviceAccount requested", () => { const serviceAccounts = { foo: { bar: "baz", }, }; SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNT_SET_SERVICE_ACCOUNT, serviceAccounts, }); expect(ACLServiceAccountsStore.getServiceAccountRaw("foo")).toEqual({ bar: "baz", }); }); }); describe("#getServiceAccount", () => { it("returns null if ServiceAccount does not exist", () => { const serviceAccounts = { foo: { bar: "baz", }, }; SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNT_SET_SERVICE_ACCOUNT, serviceAccounts, }); expect(ACLServiceAccountsStore.getServiceAccount("foobar")).toEqual(null); }); it("returns the serviceAccount requested", () => { const serviceAccounts = { foo: { bar: "baz", }, }; SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNT_SET_SERVICE_ACCOUNT, serviceAccounts, }); expect(ACLServiceAccountsStore.getServiceAccount("foo").get()).toEqual({ bar: "baz", }); expect( ACLServiceAccountsStore.getServiceAccount("foo") instanceof ServiceAccount ).toBeTruthy(); }); }); describe("#setServiceAccount", () => { it("sets serviceAccount", () => { ACLServiceAccountsStore.setServiceAccount("foo", { bar: "baz" }); expect(ACLServiceAccountsStore.getServiceAccountsDetail()).toEqual({ foo: { bar: "baz" }, }); }); }); describe("#fetchServiceAccountWithDetails", () => { beforeEach(() => { spyOn(ACLServiceAccountActions, "fetch"); spyOn(ACLServiceAccountActions, "fetchGroups"); spyOn(ACLServiceAccountActions, "fetchPermissions"); }); it("tracks serviceAccount as fetching", () => { ACLServiceAccountsStore.fetchServiceAccountWithDetails("foo"); expect(ACLServiceAccountsStore.getServiceAccountsFetching()).toEqual({ foo: { serviceAccount: false, groups: false, permissions: false, }, }); }); it("calls APIs to fetch serviceAccounts details", () => { ACLServiceAccountsStore.fetchServiceAccountWithDetails("foo"); expect(ACLServiceAccountActions.fetch).toHaveBeenCalled(); expect(ACLServiceAccountActions.fetchGroups).toHaveBeenCalled(); expect(ACLServiceAccountActions.fetchPermissions).toHaveBeenCalled(); }); }); describe("dispatcher", () => { beforeEach(() => { const serviceAccounts = []; const serviceAccountsDetails = {}; const serviceAccountsFetching = {}; // Reset state.serviceAccounts SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNTS_CHANGE, serviceAccounts, }); // Reset state.serviceAccountsDetail SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNT_SET_SERVICE_ACCOUNT, serviceAccounts: serviceAccountsDetails, }); // Reset state.serviceAccountsFetching SDK.dispatch({ type: EventTypes.ACL_SERVICE_ACCOUNT_DETAILS_FETCH_START, serviceAccountsFetching, }); }); describe("add", () => { beforeEach(() => { thisFetchAll = ACLServiceAccountsStore.fetchAll; ACLServiceAccountsStore.fetchAll = jest.fn(); }); afterEach(() => { ACLServiceAccountsStore.fetchAll = thisFetchAll; }); it("invokes fetchAll upon success", () => { SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_CREATE_SUCCESS, serviceAccountID: "foo", }); expect(ACLServiceAccountsStore.fetchAll.mock.calls.length).toEqual(1); }); it("emits event after success event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_CREATE_SUCCESS, (id) => { expect(id).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_CREATE_SUCCESS, data: { uid: "foo" }, serviceAccountID: "foo", }); }); it("emits event after error event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_CREATE_ERROR, (error, id) => { expect(id).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_CREATE_ERROR, serviceAccountID: "foo", }); }); }); describe("delete", () => { beforeEach(() => { thisFetchAll = ACLServiceAccountsStore.fetchAll; ACLServiceAccountsStore.fetchAll = jest.fn(); }); afterEach(() => { ACLServiceAccountsStore.fetchAll = thisFetchAll; }); it("invokes fetchAll upon success", () => { SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_DELETE_SUCCESS, serviceAccountID: "foo", }); expect(ACLServiceAccountsStore.fetchAll.mock.calls.length).toEqual(1); }); it("emits event after success event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_DELETE_SUCCESS, (id) => { expect(id).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_DELETE_SUCCESS, data: { uid: "foo" }, serviceAccountID: "foo", }); }); it("emits event after error event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_DELETE_ERROR, (error, id) => { expect(id).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_DELETE_ERROR, serviceAccountID: "foo", }); }); }); describe("fetch", () => { it("stores serviceAccount when event is dispatched", () => { SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_SUCCESS, data: { uid: "foo", bar: "baz" }, }); expect(ACLServiceAccountsStore.getServiceAccountRaw("foo")).toEqual({ uid: "foo", bar: "baz", }); }); it("emits event after success event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_DETAILS_SERVICE_ACCOUNT_CHANGE, (id) => { expect(id).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_SUCCESS, data: { uid: "foo" }, }); }); it("emits event after error event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_DETAILS_SERVICE_ACCOUNT_ERROR, (id) => { expect(id).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_ERROR, serviceAccountID: "foo", }); }); }); describe("fetchAll", () => { it("stores serviceAccounts when event is dispatched", () => { SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNTS_SUCCESS, data: [{ uid: "foo", bar: "baz" }], }); expect( ACLServiceAccountsStore.getServiceAccounts().getItems()[0].get() ).toEqual({ uid: "foo", bar: "baz" }); }); it("emits event after success event is dispatched", () => { const mockFn = jest.fn(); ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNTS_CHANGE, mockFn ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNTS_SUCCESS, data: [{ uid: "foo" }], }); expect(mockFn.mock.calls.length).toEqual(1); }); it("emits event after error event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNTS_ERROR, (error, id) => { expect(id).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNTS_ERROR, serviceAccountID: "foo", }); }); }); describe("groups", () => { it("stores groups when event is dispatched", () => { SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_GROUPS_SUCCESS, data: { bar: "baz" }, serviceAccountID: "foo", }); expect(ACLServiceAccountsStore.getServiceAccountRaw("foo")).toEqual({ groups: { bar: "baz" }, }); }); it("emits event after success event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_DETAILS_GROUPS_CHANGE, (id) => { expect(id).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_GROUPS_SUCCESS, serviceAccountID: "foo", }); }); it("emits event after error event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_DETAILS_GROUPS_ERROR, (id) => { expect(id).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_GROUPS_ERROR, serviceAccountID: "foo", }); }); }); describe("permissions", () => { it("stores permissions when event is dispatched", () => { SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_PERMISSIONS_SUCCESS, data: { bar: "baz" }, serviceAccountID: "foo", }); expect(ACLServiceAccountsStore.getServiceAccountRaw("foo")).toEqual({ permissions: { bar: "baz" }, }); }); it("emits event after success event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_DETAILS_PERMISSIONS_CHANGE, (id) => { expect(id).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_PERMISSIONS_SUCCESS, serviceAccountID: "foo", }); }); it("emits event after error event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_DETAILS_PERMISSIONS_ERROR, (id) => { expect(id).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_PERMISSIONS_ERROR, serviceAccountID: "foo", }); }); }); describe("update", () => { beforeEach(() => { thisFetchAll = ACLServiceAccountsStore.fetchAll; ACLServiceAccountsStore.fetchAll = jest.fn(); }); afterEach(() => { ACLServiceAccountsStore.fetchAll = thisFetchAll; }); it("invokes fetchAll upon success", () => { SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_UPDATE_SUCCESS, serviceAccountID: "foo", }); expect(ACLServiceAccountsStore.fetchAll.mock.calls.length).toEqual(1); }); it("emits event after success event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_UPDATE_SUCCESS, () => { expect(true).toEqual(true); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_UPDATE_SUCCESS, }); }); it("emits success event with the serviceAccountID", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_UPDATE_SUCCESS, (serviceAccountID) => { expect(serviceAccountID).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_UPDATE_SUCCESS, serviceAccountID: "foo", }); }); it("emits event after error event is dispatched", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_UPDATE_ERROR, () => { expect(true).toEqual(true); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_UPDATE_ERROR, }); }); it("emits error event with the serviceAccountID", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_UPDATE_ERROR, (data, serviceAccountID) => { expect(serviceAccountID).toEqual("foo"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_UPDATE_ERROR, data: "bar", serviceAccountID: "foo", }); }); it("emits error event with the error message", () => { ACLServiceAccountsStore.addChangeListener( EventTypes.ACL_SERVICE_ACCOUNT_UPDATE_ERROR, (error) => { expect(error).toEqual("bar"); } ); SDK.dispatch({ type: ActionTypes.REQUEST_ACL_SERVICE_ACCOUNT_UPDATE_ERROR, data: "bar", serviceAccountID: "foo", }); }); }); }); });
the_stack
import { Text, View, Image } from "@tarojs/components"; import Taro, { useState } from "@tarojs/taro"; import { classNames } from "../../lib"; import { IProps, imgList as imgListType, TChooseImgObj } from "../../../@types/imagePicker"; import ClIcon from "../icon"; import "./index.scss"; interface IState { imgList: { url: string; status: string; disabled?: boolean; }[]; } export default class ClImagePicker extends Taro.Component<IProps, IState> { static options = { addGlobalClass: true }; static defaultProps: IProps = { beforeDel: index => true, max: 0 }; constructor(props) { super(props); this.state = { imgList: props.imgList || [] }; } private ChooseImage() { const { chooseImgObj, max } = this.props; const { imgList } = this.state; const maxPic = max || 0; const chooseImg = chooseImgObj as TChooseImgObj; Taro.chooseImage({ count: chooseImg.count || 9, sizeType: chooseImg.sizeType || ["original", "compressed"], sourceType: chooseImg.sourceType || ["album"], success: res => { const selectArray: imgListType = res.tempFilePaths.map(url => ({ url, status: "none" })); selectArray.forEach(item => { if (!imgList.find(obj => item.url === obj.url)) { if (maxPic) { maxPic > imgList.length && imgList.push(item); } else { imgList.push(item); } } }); this.setState({ imgList }); chooseImg.success && chooseImg.success.call(this, imgList); }, fail() { chooseImg.fail && chooseImg.fail.call(this, imgList); }, complete() { chooseImg.complete && chooseImg.complete.call(this, imgList); } }); } public viewImage(url: string) { Taro.previewImage({ urls: this.state.imgList.map(item => item.url), current: url }); } public delImg(index: number) { let flag = true; const { imgList } = this.state; const del = (index: number) => { imgList.splice(index, 1); this.setState({ imgList }); }; new Promise(resolve => { if (this.props.beforeDel) { resolve(this.props.beforeDel(index)); } else { del(index); } }).then((res: boolean) => { flag = res; if (flag) { del(index); } }); } public render() { const { className, style, max } = this.props; const { imgList } = this.state; // const chooseImg = chooseImgObj || {}; const maxPic = max || 0; const imgComponent = imgList.map((item, index) => ( <View className="padding-xs bg-img bg-gray" key={item.url} style={{ borderRadius: "6px", position: "relative" }} onClick={() => { this.viewImage.call(this, item.url); }} > <Image src={item.url} mode="widthFix" style={{ width: "100%", position: "absolute", left: "50%", top: "50%", right: "0", bottom: "0", transform: "translate(-50%, -50%)" }} /> {item.status === "none" && !item.disabled ? ( <View className="cu-tag bg-red" onClick={e => { e.stopPropagation(); this.delImg.call(this, index); }} style={{ backgroundColor: "rgba(355, 355, 355, 0.8)" }} > <ClIcon iconName="close" color="black" size="xsmall" /> </View> ) : ( "" )} { <View className="cu-tag" style={{ backgroundColor: "rgba(355, 355, 355, 0.8)", display: `${item.status === "fail" ? "" : "none"}` }} > <ClIcon iconName="warnfill" size="xsmall" color="red" /> </View> } { <View className="cu-tag" style={{ backgroundColor: "rgba(355, 355, 355, 0.8)", display: `${item.status === "success" ? "" : "none"}` }} > <ClIcon iconName="roundcheckfill" size="xsmall" color="olive" /> </View> } { <View className="cu-tag" style={{ backgroundColor: "rgba(355, 355, 355, 0.8)", display: `${item.status === "loading" ? "" : "none"}` }} > <View className="imagePicker-rotate-360"> <ClIcon iconName="loading" size="xsmall" color="blue" /> </View> </View> } </View> )); return ( <View className={classNames("cu-form-group", className)} style={Object.assign({}, style)} > <View className="grid col-4 grid-square flex-sub"> {imgComponent} {(maxPic === 0 || maxPic !== imgList.length) && ( <View className="padding-xs bg-gray" onClick={this.ChooseImage.bind(this)} style={{ borderRadius: "6px" }} > <Text className="cuIcon-cameraadd" /> </View> )} </View> </View> ); } } // export default function ClImagePicker(props: IProps) { // const chooseImgObj = props.chooseImgObj || {}; // const maxPic = props.max || 0; // const [imgList, setImgList] = useState(() => { // const tempImg = props.imgList || []; // return [...tempImg]; // }); // const ChooseImage = () => { // Taro.chooseImage({ // count: chooseImgObj.count || 9, // sizeType: chooseImgObj.sizeType || ["original", "compressed"], // sourceType: chooseImgObj.sourceType || ["album"], // success: res => { // console.log(res); // const selectArray: imgListType = res.tempFilePaths.map(url => ({ // url, // status: "none" // })); // selectArray.forEach(item => { // if (!imgList.find(obj => item.url === obj.url)) { // if (maxPic) { // maxPic > imgList.length && imgList.push(item); // } else { // imgList.push(item); // } // } // }); // setImgList(imgList); // chooseImgObj.success && chooseImgObj.success.call(this, imgList); // }, // fail() { // chooseImgObj.fail && chooseImgObj.fail.call(this, imgList); // }, // complete() { // chooseImgObj.complete && chooseImgObj.complete.call(this, imgList); // } // }); // }; // const viewImage = (url: string) => { // Taro.previewImage({ // urls: imgList.map(item => item.url), // current: url // }); // }; // const delImg = (index: number) => { // let flag = true; // const del = (index: number) => { // imgList.splice(index, 1); // setImgList(imgList); // }; // new Promise(resolve => { // if (props.beforeDel) { // resolve(props.beforeDel(index)); // } else { // del(index); // } // }).then((res: boolean) => { // flag = res; // if (flag) { // del(index); // } // }); // }; // const imgComponent = imgList.map((item, index) => ( // <View // className="padding-xs bg-img bg-gray" // key={item.url} // style={{ borderRadius: "6px", position: "relative" }} // onClick={() => { // viewImage(item.url); // }} // > // <Image // src={item.url} // mode="widthFix" // style={{ // width: "100%", // position: "absolute", // left: "0", // top: "0", // right: "0", // bottom: "0", // display: "flex", // justifyContent: "center", // alignItems: "center" // }} // /> // {item.status === "none" ? ( // <View // className="cu-tag bg-red" // onClick={e => { // e.stopPropagation(); // delImg(index); // }} // style={{ backgroundColor: "rgba(355, 355, 355, 0.8)" }} // > // <ClIcon iconName="close" color="black" size="xsmall" /> // </View> // ) : ( // "" // )} // { // <View // className="cu-tag" // style={{ // backgroundColor: "rgba(355, 355, 355, 0.8)", // display: `${item.status === "fail" ? "" : "none"}` // }} // > // <ClIcon iconName="warnfill" size="xsmall" color="red" /> // </View> // } // { // <View // className="cu-tag" // style={{ // backgroundColor: "rgba(355, 355, 355, 0.8)", // display: `${item.status === "success" ? "" : "none"}` // }} // > // <ClIcon iconName="roundcheckfill" size="xsmall" color="olive" /> // </View> // } // { // <View // className="cu-tag" // style={{ // backgroundColor: "rgba(355, 355, 355, 0.8)", // display: `${item.status === "loading" ? "" : "none"}` // }} // > // <View className="imagePicker-rotate-360"> // <ClIcon iconName="loading" size="xsmall" color="blue" /> // </View> // </View> // } // </View> // )); // return ( // <View // className={classNames("cu-form-group", props.className)} // style={Object.assign({}, props.style)} // > // <View className="grid col-4 grid-square flex-sub"> // {imgComponent} // {(maxPic === 0 || maxPic !== imgList.length) && ( // <View // className="padding-xs bg-gray" // onClick={ChooseImage} // style={{ borderRadius: "6px" }} // > // <Text className="cuIcon-cameraadd" /> // </View> // )} // </View> // </View> // ); // } // ClImagePicker.defaultProps = { // beforeDel: index => true, // max: 0 // } as IProps; // ClImagePicker.options = { // addGlobalClass: true // };
the_stack
import { Fragment, FunctionComponent, h } from 'preact'; import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'preact/hooks'; import * as GoToFileIcon from 'vscode-codicons/src/icons/go-to-file.svg'; import { binarySearch } from 'vscode-js-profile-core/out/esm/array'; import { Icon } from 'vscode-js-profile-core/out/esm/client/icons'; import { MiddleOut } from 'vscode-js-profile-core/out/esm/client/middleOutCompression'; import { useCssVariables } from 'vscode-js-profile-core/out/esm/client/useCssVariables'; import { usePersistedState } from 'vscode-js-profile-core/out/esm/client/usePersistedState'; import { useWindowSize } from 'vscode-js-profile-core/out/esm/client/useWindowSize'; import { classes } from 'vscode-js-profile-core/out/esm/client/util'; import { IVscodeApi, VsCodeApi } from 'vscode-js-profile-core/out/esm/client/vscodeApi'; import { decimalFormat, getLocationText } from 'vscode-js-profile-core/out/esm/cpu/display'; import { Category, ILocation, IProfileModel } from 'vscode-js-profile-core/out/esm/cpu/model'; import { IOpenDocumentMessage } from 'vscode-js-profile-core/out/esm/cpu/types'; import styles from './flame-graph.css'; import { IColumn, IColumnLocation } from './stacks'; import { TextCache } from './textCache'; import { setupGl } from './webgl/boxes'; export const enum Constants { BoxHeight = 20, TextColor = '#fff', BoxColor = '#000', TimelineHeight = 22, TimelineLabelSpacing = 200, MinWindow = 0.005, ExtraYBuffer = 300, DefaultStackLimit = 7, } const pickColor = (location: IColumnLocation): number => { if (location.category === Category.System) { return -1; } const hash = location.graphId * 5381; // djb2's prime, just some bogus stuff return hash & 0xff; }; export interface IBox { column: number; row: number; x1: number; y1: number; x2: number; y2: number; color: number; level: number; text: string; category: number; loc: IColumnLocation; } const buildBoxes = (columns: ReadonlyArray<IColumn>, filtered: ReadonlyArray<number>) => { const boxes: Map<number, IBox> = new Map(); let maxY = 0; for (let x = 0; x < columns.length; x++) { const col = columns[x]; const highlightY = filtered[x]; for (let y = 0; y < col.rows.length; y++) { const loc = col.rows[y]; if (typeof loc === 'number') { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion getBoxInRowColumn(columns, boxes, x, y)!.x2 = col.x2; } else { const y1 = Constants.BoxHeight * y + Constants.TimelineHeight; const y2 = y1 + Constants.BoxHeight; boxes.set(loc.graphId, { column: x, row: y, x1: col.x1, x2: col.x2, y1, y2, level: y, text: loc.callFrame.functionName, color: pickColor(loc), category: y <= highlightY ? loc.category : Category.Deemphasized, loc, }); maxY = Math.max(y2, maxY); } } } return { boxById: boxes, maxY, }; }; export interface IBounds { minX: number; maxX: number; y: number; level: number; } const enum LockBound { None = 0, Y = 1 << 0, MinX = 1 << 1, MaxX = 1 << 2, } interface IDrag { timestamp: number; pageXOrigin: number; pageYOrigin: number; original: IBounds; xPerPixel: number; lock: LockBound; } const enum HighlightSource { Hover, Keyboard, } const clamp = (min: number, v: number, max: number) => Math.max(Math.min(v, max), min); const timelineFormat = new Intl.NumberFormat(undefined, { maximumSignificantDigits: 3, minimumSignificantDigits: 3, }); const dpr = window.devicePixelRatio || 1; const getBoxInRowColumn = ( columns: ReadonlyArray<IColumn>, boxes: ReadonlyMap<number, IBox>, column: number, row: number, ) => { let candidate = columns[column]?.rows[row]; if (typeof candidate === 'number') { candidate = columns[candidate].rows[row]; } return candidate !== undefined ? boxes.get((candidate as { graphId: number }).graphId) : undefined; }; interface ISerializedState { focusedId?: number; bounds?: IBounds; } export interface ICanvasSize { width: number; height: number; } /** * Gets the floating point precision threshold for calculating positions and * intersections within the given set of bounds. */ const epsilon = (bounds: IBounds) => (bounds.maxX - bounds.minX) / 100_000; export const FlameGraph: FunctionComponent<{ columns: ReadonlyArray<IColumn>; filtered: ReadonlyArray<number>; model: IProfileModel; }> = ({ columns, model, filtered }) => { const vscode = useContext(VsCodeApi) as IVscodeApi<ISerializedState>; const webCanvas = useRef<HTMLCanvasElement>(); const webContext = useMemo(() => webCanvas.current?.getContext('2d'), [webCanvas.current]); const glCanvas = useRef<HTMLCanvasElement>(); const windowSize = useWindowSize(); const [canvasSize, setCanvasSize] = useState<ICanvasSize>({ width: 100, height: 100 }); const [hovered, setHovered] = useState<{ box: IBox; src: HighlightSource } | undefined>( undefined, ); const [drag, setDrag] = useState<IDrag | undefined>(undefined); const [showInfo, setShowInfo] = useState(false); const cssVariables = useCssVariables(); const rawBoxes = useMemo(() => buildBoxes(columns, filtered), [columns, filtered]); const clampY = Math.max(0, rawBoxes.maxY - canvasSize.height + Constants.ExtraYBuffer); const [focused, setFocused] = useState<IBox | undefined>(undefined); const [bounds, setBounds] = usePersistedState<IBounds>('bounds', { minX: 0, maxX: 1, y: 0, level: 0, }); const gl = useMemo( () => glCanvas.current && setupGl({ canvas: glCanvas.current, focusColor: cssVariables.focusBorder, primaryColor: cssVariables['charts-red'], boxes: [...rawBoxes.boxById.values()], scale: dpr, }), [glCanvas.current], ); useEffect(() => gl?.setBoxes([...rawBoxes.boxById.values()]), [rawBoxes]); useEffect(() => gl?.setBounds(bounds, canvasSize, dpr), [bounds, canvasSize]); useEffect(() => gl?.setFocusColor(cssVariables.focusBorder), [cssVariables.focusBorder]); useEffect(() => gl?.setPrimaryColor(cssVariables['charts-red']), [cssVariables['charts-red']]); useEffect(() => gl?.setFocused(focused?.loc.graphId), [focused]); useEffect(() => gl?.setHovered(hovered?.box.loc.graphId), [hovered]); useEffect(() => { if (focused) { setShowInfo(true); } }, [focused]); const openBox = useCallback( (box: IBox, evt: { altKey: boolean }) => { const src = box.loc.src; if (!src?.source.path) { return; } vscode.postMessage<IOpenDocumentMessage>({ type: 'openDocument', location: src, callFrame: box.loc.callFrame, toSide: evt.altKey, }); }, [vscode], ); const textCache = useMemo( () => new TextCache( `${Constants.BoxHeight / 1.9}px ${cssVariables['editor-font-family']}`, Constants.TextColor, dpr, ), [cssVariables], ); useEffect(() => { if (webContext) { webContext.textBaseline = 'middle'; webContext.scale(dpr, dpr); } }, [webContext, canvasSize]); // Re-render box labels when data changes useEffect(() => { if (!webContext) { return; } webContext.clearRect(0, Constants.TimelineHeight, canvasSize.width, canvasSize.height); webContext.save(); webContext.beginPath(); webContext.rect(0, Constants.TimelineHeight, canvasSize.width, canvasSize.height); for (const box of rawBoxes.boxById.values()) { if (box.y2 < bounds.y) { continue; } if (box.y1 > bounds.y + canvasSize.height) { continue; } const xScale = canvasSize.width / (bounds.maxX - bounds.minX); const x1 = Math.max(0, (box.x1 - bounds.minX) * xScale); if (x1 > canvasSize.width) { continue; } const x2 = (box.x2 - bounds.minX) * xScale; if (x2 < 0) { continue; } const width = x2 - x1; if (width < 10) { continue; } textCache.drawText( webContext, box.text, x1 + 3, box.y1 - bounds.y + 3, width - 6, Constants.BoxHeight, ); } webContext.clip(); webContext.restore(); }, [webContext, bounds, rawBoxes, canvasSize, cssVariables]); // Re-render the zoom indicator when bounds change useEffect(() => { if (!webContext) { return; } webContext.clearRect(0, 0, webContext.canvas.width, Constants.TimelineHeight); webContext.fillStyle = cssVariables['editor-foreground']; webContext.font = webContext.textAlign = 'right'; webContext.strokeStyle = cssVariables['editorRuler-foreground']; webContext.lineWidth = 1 / dpr; const labels = Math.round(canvasSize.width / Constants.TimelineLabelSpacing); const spacing = canvasSize.width / labels; const timeRange = model.duration * (bounds.maxX - bounds.minX); const timeStart = model.duration * bounds.minX; webContext.beginPath(); for (let i = 1; i <= labels; i++) { const time = (i / labels) * timeRange + timeStart; const x = i * spacing; webContext.fillText( `${timelineFormat.format(time / 1000)}ms`, x - 3, Constants.TimelineHeight / 2, ); webContext.moveTo(x, 0); webContext.lineTo(x, Constants.TimelineHeight); } webContext.stroke(); webContext.textAlign = 'left'; }, [webContext, model, canvasSize, bounds, cssVariables]); // Update the canvas size when the window size changes, and on initial render useEffect(() => { if (!webCanvas.current || !glCanvas.current) { return; } const { width, height } = (webCanvas.current .parentElement as HTMLElement).getBoundingClientRect(); if (width === canvasSize.width && height === canvasSize.height) { return; } for (const canvas of [webCanvas.current, glCanvas.current]) { canvas.style.width = `${width}px`; canvas.width = width * dpr; canvas.style.height = `${height}px`; canvas.height = height * dpr; } setCanvasSize({ width, height }); }, [windowSize]); // Callback that zoomes into the given box. const zoomToBox = useCallback( (box: IBox) => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion setBounds({ minX: box.x1, maxX: box.x2, y: clamp(0, box.y1 > bounds.y + canvasSize.height ? box.y1 : bounds.y, clampY), level: box.level, }); setFocused(box); }, [clampY, canvasSize.height, bounds], ); // Key event handler, deals with focus navigation and escape/enter const onKeyDown = useCallback( (evt: KeyboardEvent) => { switch (evt.key) { case 'Escape': // If there's a tooltip open, close that on first escape return hovered?.src === HighlightSource.Keyboard ? setHovered(undefined) : showInfo ? setShowInfo(false) : setBounds({ minX: 0, maxX: 1, y: 0, level: 0 }); case 'Enter': if ((evt.metaKey || evt.ctrlKey) && hovered) { return openBox(hovered.box, evt); } return focused && zoomToBox(focused); case 'Space': return focused && zoomToBox(focused); default: // fall through } if (!focused) { return; } let nextFocus: IBox | false | undefined; switch (evt.key) { case 'ArrowRight': for ( let x = focused.column + 1; x < columns.length && columns[x].x1 + epsilon(bounds) < bounds.maxX; x++ ) { const box = getBoxInRowColumn(columns, rawBoxes.boxById, x, focused.row); if (box && box !== focused) { nextFocus = box; break; } } break; case 'ArrowLeft': for ( let x = focused.column - 1; x >= 0 && columns[x].x2 - epsilon(bounds) > bounds.minX; x-- ) { const box = getBoxInRowColumn(columns, rawBoxes.boxById, x, focused.row); if (box && box !== focused) { nextFocus = box; break; } } break; case 'ArrowUp': nextFocus = getBoxInRowColumn(columns, rawBoxes.boxById, focused.column, focused.row - 1); break; case 'ArrowDown': { let x = focused.column; do { nextFocus = getBoxInRowColumn(columns, rawBoxes.boxById, x, focused.row + 1); } while (!nextFocus && columns[++x]?.rows[focused.row] === focused.column); } break; default: break; } if (nextFocus) { setFocused(nextFocus); setHovered({ box: nextFocus, src: HighlightSource.Keyboard }); } }, [zoomToBox, focused, hovered, rawBoxes, showInfo], ); // Keyboard events useEffect(() => { window.addEventListener('keydown', onKeyDown); return () => window.removeEventListener('keydown', onKeyDown); }, [onKeyDown]); const getBoxUnderCursor = useCallback( (evt: MouseEvent) => { if (!webCanvas.current) { return; } const { top, left, width } = webCanvas.current.getBoundingClientRect(); const fromTop = evt.pageY - top; const fromLeft = evt.pageX - left; if (fromTop < Constants.TimelineHeight) { return; } const x = (fromLeft / width) * (bounds.maxX - bounds.minX) + bounds.minX; const col = Math.abs(binarySearch(columns, c => c.x2 - x)) - 1; if (!columns[col] || columns[col].x1 > x) { return; } const row = Math.floor((fromTop + bounds.y - Constants.TimelineHeight) / Constants.BoxHeight); return getBoxInRowColumn(columns, rawBoxes.boxById, col, row); }, [webCanvas, bounds, columns, rawBoxes], ); // Listen for drag events on the window when it's running useEffect(() => { if (!drag) { return; } const { original, pageXOrigin, xPerPixel, pageYOrigin, lock } = drag; const onMove = (evt: MouseEvent) => { const range = original.maxX - original.minX; let minX: number; let maxX: number; if (!(lock & LockBound.MinX)) { const upper = lock & LockBound.MaxX ? bounds.maxX - Constants.MinWindow : 1 - range; minX = clamp(0, original.minX - (evt.pageX - pageXOrigin) * xPerPixel, upper); maxX = lock & LockBound.MaxX ? original.maxX : Math.min(1, minX + range); } else { minX = original.minX; maxX = clamp( minX + Constants.MinWindow, original.maxX - (evt.pageX - pageXOrigin) * xPerPixel, 1, ); } const y = lock & LockBound.Y ? bounds.y : clamp(0, original.y - (evt.pageY - pageYOrigin), clampY); setBounds({ minX, maxX, y, level: bounds.level }); }; const onUp = (evt: MouseEvent) => { onMove(evt); setDrag(undefined); }; document.addEventListener('mousemove', onMove); document.addEventListener('mouseleave', onUp); document.addEventListener('mouseup', onUp); return () => { document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseleave', onUp); document.removeEventListener('mouseup', onUp); }; }, [clampY, drag]); const onMouseMove = useCallback( (evt: MouseEvent) => { if (!webContext || drag) { return; } const box = getBoxUnderCursor(evt); if (!box && hovered?.src === HighlightSource.Keyboard) { // don't hide tooltips created by focus change on mousemove return; } setHovered(box ? { box, src: HighlightSource.Hover } : undefined); }, [drag || getBoxUnderCursor, webContext, canvasSize, hovered, rawBoxes], ); const onWheel = useCallback( (evt: WheelEvent) => { if (!webCanvas.current) { return; } if (evt.altKey) { setBounds({ ...bounds, y: clamp(0, bounds.y + evt.deltaY, clampY) }); return; } const { left, width } = webCanvas.current.getBoundingClientRect(); if (evt.shiftKey) { const deltaX = clamp( 0 - bounds.minX, (evt.deltaY / width) * (bounds.maxX - bounds.minX), 1 - bounds.maxX, ); setBounds({ ...bounds, minX: bounds.minX + deltaX, maxX: bounds.maxX + deltaX }); return; } const range = bounds.maxX - bounds.minX; const center = bounds.minX + (range * (evt.pageX - left)) / width; const scale = evt.deltaY / -400; setBounds({ minX: Math.max(0, bounds.minX + scale * (center - bounds.minX)), maxX: Math.min(1, bounds.maxX - scale * (bounds.maxX - center)), y: bounds.y, level: bounds.level, }); evt.preventDefault(); }, [clampY, webCanvas.current, drag || bounds], ); const onMouseDown = useCallback( (evt: MouseEvent) => { setDrag({ timestamp: Date.now(), pageXOrigin: evt.pageX, pageYOrigin: evt.pageY, xPerPixel: (bounds.maxX - bounds.minX) / canvasSize.width, original: bounds, lock: LockBound.None, }); evt.preventDefault(); }, [canvasSize, drag || bounds], ); const onMouseUp = useCallback( (evt: MouseEvent) => { if (!drag) { return; } const isClick = Date.now() - drag.timestamp < 500 && Math.abs(evt.pageX - drag.pageXOrigin) < 100 && Math.abs(evt.pageY - drag.pageYOrigin) < 100; if (!isClick) { return; } const box = getBoxUnderCursor(evt); if (box && (evt.ctrlKey || evt.metaKey)) { openBox(box, evt); } else if (box) { zoomToBox(box); } else { setBounds({ minX: 0, maxX: 1, y: 0, level: 0 }); } setHovered(undefined); setDrag(undefined); evt.stopPropagation(); evt.preventDefault(); }, [drag, getBoxUnderCursor, openBox, zoomToBox], ); const onMouseLeave = useCallback( (evt: MouseEvent) => { onMouseUp(evt); setHovered(undefined); }, [onMouseUp], ); const onFocus = useCallback(() => { if (focused) { setHovered({ box: focused, src: HighlightSource.Keyboard }); return; } const firstCol = Math.abs(binarySearch(columns, c => c.x2 - bounds.minX)); const firstBox = getBoxInRowColumn(columns, rawBoxes.boxById, firstCol, 0); if (firstBox) { setFocused(firstBox); setHovered({ box: firstBox, src: HighlightSource.Keyboard }); } }, [rawBoxes, columns, drag || bounds, focused]); return ( <Fragment> <DragHandle bounds={bounds} current={drag} canvasWidth={canvasSize.width} startDrag={setDrag} /> <canvas ref={webCanvas} style={{ cursor: hovered ? 'pointer' : 'default' }} role="application" tabIndex={0} onFocus={onFocus} onMouseDown={onMouseDown} onMouseUp={onMouseUp} onMouseLeave={onMouseLeave} onMouseMove={onMouseMove} onWheel={onWheel} /> <canvas ref={glCanvas} style={{ position: 'absolute', top: Constants.TimelineHeight, left: 0, right: 0, bottom: 0, pointerEvents: 'none', zIndex: -1, }} /> {hovered && ( <Tooltip canvasWidth={canvasSize.width} canvasHeight={canvasSize.height} left={(hovered.box.x1 - bounds.minX) / (bounds.maxX - bounds.minX)} upperY={canvasSize.height - hovered.box.y1 + bounds.y} lowerY={hovered.box.y2 - bounds.y} src={hovered.src} location={hovered.box.loc} /> )} {focused && showInfo && ( <InfoBox columns={columns} boxes={rawBoxes.boxById} box={focused} model={model} setFocused={setFocused} /> )} </Fragment> ); }; const DragHandle: FunctionComponent<{ canvasWidth: number; bounds: IBounds; current: IDrag | undefined; startDrag: (bounds: IDrag) => void; }> = ({ current, bounds, startDrag, canvasWidth }) => { const start = useCallback( (evt: MouseEvent, lock: LockBound, original: IBounds = bounds) => { startDrag({ timestamp: Date.now(), pageXOrigin: evt.pageX, pageYOrigin: evt.pageY, original, xPerPixel: -1 / canvasWidth, lock: lock | LockBound.Y, }); evt.preventDefault(); evt.stopPropagation(); }, [canvasWidth, bounds], ); const range = bounds.maxX - bounds.minX; const lock = current?.lock ?? 0; return ( <div className={classes(styles.handle, current && styles.active)} style={{ height: Constants.TimelineHeight }} > <div className={classes(styles.bg, lock === LockBound.Y && styles.active)} onMouseDown={useCallback((evt: MouseEvent) => start(evt, LockBound.Y), [start])} style={{ transform: `scaleX(${range}) translateX(${(bounds.minX / range) * 100}%)` }} /> <div className={classes(styles.bookend, lock & LockBound.MaxX && styles.active)} style={{ transform: `translateX(${bounds.minX * 100}%)` }} > <div style={{ left: 0 }} onMouseDown={useCallback((evt: MouseEvent) => start(evt, LockBound.MaxX), [start])} /> </div> <div className={classes(styles.bookend, lock & LockBound.MinX && styles.active)} style={{ transform: `translateX(${(bounds.maxX - 1) * 100}%)` }} > <div style={{ right: 0 }} onMouseDown={useCallback((evt: MouseEvent) => start(evt, LockBound.MinX), [start])} /> </div> </div> ); }; const Tooltip: FunctionComponent<{ canvasWidth: number; canvasHeight: number; left: number; upperY: number; lowerY: number; location: ILocation; src: HighlightSource; }> = ({ left, lowerY, upperY, src, location, canvasWidth, canvasHeight }) => { const label = getLocationText(location); const above = lowerY + 300 > canvasHeight && lowerY > canvasHeight / 2; const file = label?.split(/\\|\//g).pop(); return ( <div className={styles.tooltip} aria-live="polite" aria-atomic={true} style={{ left: clamp(0, canvasWidth * left + 10, canvasWidth - 400), top: above ? 'initial' : lowerY + 10, bottom: above ? upperY + 10 : 'initial', }} > <dl> <dt>Function</dt> <dd className={styles.function}>{location.callFrame.functionName}</dd> {label && ( <Fragment> <dt>File</dt> <dd aria-label={file} className={classes(styles.label, location.src && styles.clickable)} > <MiddleOut aria-hidden={true} endChars={file?.length} text={label} /> </dd> </Fragment> )} <dt className={styles.time}>Self Time</dt> <dd className={styles.time}>{decimalFormat.format(location.selfTime / 1000)}ms</dd> <dt className={styles.time}>Aggregate Time</dt> <dd className={styles.time}>{decimalFormat.format(location.aggregateTime / 1000)}ms</dd> </dl> <div className={styles.hint}> Ctrl+{src === HighlightSource.Keyboard ? 'Enter' : 'Click'} to jump to file </div> </div> ); }; const InfoBox: FunctionComponent<{ box: IBox; model: IProfileModel; columns: ReadonlyArray<IColumn>; boxes: ReadonlyMap<number, IBox>; setFocused(box: IBox): void; }> = ({ columns, boxes, box, model, setFocused }) => { const originalLocation = model.locations[box.loc.id]; const localLocation = box.loc; const [limitedStack, setLimitedStack] = useState(true); useEffect(() => setLimitedStack(true), [box]); const stack = useMemo(() => { const stack: IBox[] = [box]; for (let row = box.row - 1; row >= 0 && stack.length; row--) { const b = getBoxInRowColumn(columns, boxes, box.column, row); if (b) { stack.push(b); } } return stack; }, [box, columns, boxes]); const shouldTruncateStack = stack.length >= Constants.DefaultStackLimit + 3 && limitedStack; return ( <div className={styles.info}> <dl> <dt>Self Time</dt> <dd>{decimalFormat.format(localLocation.selfTime / 1000)}ms</dd> <dt>Total Time</dt> <dd>{decimalFormat.format(localLocation.aggregateTime / 1000)}ms</dd> <dt> Self Time<small>Entire Profile</small> </dt> <dd>{decimalFormat.format(originalLocation.selfTime / 1000)}ms</dd> <dt> Total Time<small>Entire Profile</small> </dt> <dd>{decimalFormat.format(originalLocation.aggregateTime / 1000)}ms</dd> </dl> <ol start={0}> {stack.map( (b, i) => (!shouldTruncateStack || i < Constants.DefaultStackLimit) && ( <li key={i}> <BoxLink box={b} onClick={setFocused} link={i > 0} /> </li> ), )} {shouldTruncateStack && ( <li> <a onClick={() => setLimitedStack(false)}> <em>{stack.length - Constants.DefaultStackLimit} more...</em> </a> </li> )} </ol> </div> ); }; const BoxLink: FunctionComponent<{ box: IBox; onClick(box: IBox): void; link?: boolean }> = ({ box, onClick, link, }) => { const vscode = useContext(VsCodeApi) as IVscodeApi; const open = useCallback( (evt: { altKey: boolean }) => { const src = box.loc.src; if (!src?.source.path) { return; } vscode.postMessage<IOpenDocumentMessage>({ type: 'openDocument', location: src, callFrame: box.loc.callFrame, toSide: evt.altKey, }); }, [vscode, box], ); const click = useCallback(() => onClick(box), [box, onClick]); const locText = getLocationText(box.loc); const linkContent = ( <Fragment> {box.loc.callFrame.functionName} <em>({locText})</em> </Fragment> ); return ( <Fragment> {link ? <a onClick={click}>{linkContent}</a> : linkContent} {box.loc.src?.source.path && ( <Icon i={GoToFileIcon} className={styles.goToFile} onClick={open} role="button" title="Go to File" /> )} </Fragment> ); };
the_stack
import { should, expect } from 'chai'; should(); import { KeyedDeep, ChangeMap } from '../keyed-deep'; import { State } from '../state'; describe('KeyedDeep', () => { describe('.key()', () => { it('should return a state with correct initial value even if unbound.', () => { let s = new KeyedDeep(new State([{id: 1, name: 'hellow'}, {id: 2, name: 'world'}]), _ => _.id); let k = s.key(1); expect(k.value).to.eql({id: 1, name: 'hellow'}); }); it('should have value of `undefined` when the given key is not in parent state even if unbound.', () => { let s = new KeyedDeep(new State([]), _ => _.id); let k = s.key(1); expect(k.value).to.be.undefined; }); it('should have the correct value of given key in parent state.', () => { let s = new KeyedDeep(new State([{id: 1, name: 'Jack'}, {id: 2, name: 'Jill'}]), (_) => _.id); let k = s.key(1).bind(); k.value.should.eql({id: 1, name: 'Jack'}); s.value = [{id: 1, name: 'John'}, {id: 2, name: 'Jill'}]; k.value.should.eql({id: 1, name: 'John'}); }); it('should reemit when the value with given key on parent state changes.', () => { let s = new KeyedDeep(new State([{id: 12, name: 'Jack'}, {id: 22, name: 'Jill'}]), (_) => _.id); let k = s.key(12).bind(); let r = 0; k.subscribe(() => r++); r.should.equal(1); // --> initial value s.value = [{id: 20, name: 'John'}, {id: 12, name: 'Jack'}, {id: 22, name: 'Jill'}]; r.should.equal(1); // --> no changes s.value = [{id: 20, name: 'John'}, {id: 12, name: 'Joseph'}, {id: 22, name: 'Jill'}]; r.should.equal(2); // --> change }); it('should cause the parent to reemit when the value of bound key changes.', () => { let s = new KeyedDeep(new State([{id: 12, name: 'Jack'}, {id: 22, name: 'Jill'}]), (_) => _.id); let k = s.key(12).bind(); let r = 0; s.subscribe(() => r++); r.should.equal(1); // --> initial value k.value = {id: 12, name: 'Joseph'}; s.value.should.eql([{id: 12, name: 'Joseph'}, {id: 22, name: 'Jill'}]); r.should.equal(2); // --> reemission }); it('should not cause a reemit on parent when it receives a down-propagated value.', () => { let s = new KeyedDeep(new State([{id: 12, name: 'Jack'}, {id: 22, name: 'Jill'}]), (_) => _.id); let k = s.key(12).bind(); let r = 0; s.subscribe(() => r++); r.should.equal(1); // --> initial value }); it('should sync values of same key.', () => { let s = new KeyedDeep(new State([{id: 12, name: 'Jack'}, {id: 22, name: 'Jill'}]), (_) => _.id); let k1 = s.key(12).bind(); let k2 = s.key(12).bind(); k1.value = { id: 12, name: 'Josh' }; k2.value.name.should.equal('Josh'); }); it('should efficiently sync values of same key.', () => { let s = new KeyedDeep(new State([{id: 12, name: 'Jack'}, {id: 22, name: 'Jill'}]), (_) => _.id); let k1 = s.key(12).bind(); let k2 = s.key(12).bind(); let r = 0; k2.subscribe(() => r++); r.should.equal(1); // --> initial value s.value = [{id: 12, name: 'Jack'}, {id: 22, name: 'Jeff'}]; r.should.equal(1); // --> no change k1.value = {id: 12, name: 'Josh'}; r.should.equal(2); // --> no change }); it('should propagate changes in grandchild states to grandparents as well.', () => { let gp = new KeyedDeep(new State([{id: 12, name: 'Jack'}, {id: 22, name: 'Jill'}]), (_) => _.id); let c = gp.key(12).bind(); let gc = c.sub('name').bind(); let r = 0; gp.subscribe(() => r++); r.should.equal(1); // --> initial value let r2 = 0; c.subscribe(() => r2++); r2.should.equal(1); // --> initial value gc.value = 'Jeff'; r2.should.equal(2); // --> change r.should.equal(2); // --> change c.value.should.eql({id: 12, name: 'Jeff'}); gp.value.should.eql([{id: 12, name: 'Jeff'}, {id: 22, name: 'Jill'}]); }); it('should keep values of grandchild states sync.', () => { let gp = new KeyedDeep(new State([{id: 12, name: 'Jack'}, {id: 22, name: 'Jill'}]), (_) => _.id); let gc1 = gp.key(12).bind().sub('name').bind(); let gc2 = gp.key(12).bind().sub('name').bind(); gc1.value = 'Jeff'; gc2.value.should.equal('Jeff'); }); it('should sync values of grandchild states efficiently.', () => { let gp = new KeyedDeep(new State([{id: 12, name: 'Jack'}, {id: 22, name: 'Jill'}]), (_) => _.id); let r = 0; gp.subscribe(() => r++); let c1 = gp.key(12).bind(); let rc1 = 0; c1.subscribe(() => rc1++); let gc1 = c1.sub('name').bind(); let rgc1 = 0; gc1.subscribe(() => rgc1++); let c2 = gp.key(12).bind(); let rc2 = 0; c2.subscribe(() => rc2++); let gc2 = c2.sub('name').bind(); let rgc2 = 0; gc2.subscribe(() => rgc2++); r.should.equal(1); // --> initial value rc1.should.equal(1); rgc1.should.equal(1); rc2.should.equal(1); rgc2.should.equal(1); c2.value = {id: 12, name: 'Jeff'}; r.should.equal(2); rc1.should.equal(2); rgc1.should.equal(2); rc2.should.equal(2); rgc2.should.equal(2); gc1.value = 'John'; r.should.equal(3); rc1.should.equal(3); rgc1.should.equal(3); rc2.should.equal(3); rgc2.should.equal(3); }); }); describe('.index()', () => { it('should emit the index of the given key in the array.', () => { let s = new KeyedDeep(new State([{id: 'john'}, {id: 'jack'}]), (_) => _.id); let r = <string[]>[]; s.index('john').subscribe(v => r.push(v)); s.value = [{id: 'jack'}, {id: 'john'}]; r.should.eql(['0', '1']); }); it('should be -1 when the key is not in the array', () => { let s = new KeyedDeep(new State([{id: 'jack'}]), (_) => _.id); let r = <string[]>[]; s.index('john').subscribe(v => r.push(v)); s.value = [{id: 'jack'}, {id: 'john'}]; s.value = []; r.should.eql([-1, '1', -1]); }); it('should only emit when the index changes, regardless of value changes.', () => { let s = new KeyedDeep(new State([{id: 'john', age: 23}, {id: 'jack', age: 24}]), (_) => _.id); let r = <string[]>[]; s.index('john').subscribe(v => r.push(v)); r.should.eql(['0']); // --> initial index s.value = [{id: 'john', age: 23}, {id: 'jill', age: 24}, {id: 'jack', age: 24}]; r.should.eql(['0']); // --> no change in index s.value = [{id: 'john', age: 26}, {id: 'jill', age: 24}, {id: 'jack', age: 24}]; r.should.eql(['0']); // --> no change in index yet s.value = [{id: 'jill', age: 24}, {id: 'jack', age: 24}, {id: 'john', age: 26}]; r.should.eql(['0', '2']); // --> index change }); }); describe('.keys', () => { it('should be an empty array for an unbound state.', () => { let s = new KeyedDeep(new State([{id: 'john', age: 23}, {id: 'jack', age: 24}]), (_) => _.id); s.keys.should.eql([]); }); it('should contain all of the keys of the state.', () => { let s = new KeyedDeep(new State([{id: 'john', age: 23}, {id: 'jack', age: 24}]), (_) => _.id); s.bind(); s.keys.should.have.deep.members(['john', 'jack']); s.value = [{id: 'john', age: 23}, {id: 'jack', age: 24}, {id: 'jill', age: 25}]; s.keys.should.have.deep.members(['john', 'jack', 'jill']); s.value = [{id: 'jack', age: 24}, {id: 'jill', age: 25}]; s.keys.should.have.deep.members(['jack', 'jill']); }); }); describe('.changes', () => { it('should emit whenever the state changes.', () => { let s = new KeyedDeep(new State([{id: 'john', age: 23}, {id: 'jack', age: 24}]), (_) => _.id); let k = s.key('john').bind(); let r = 0; s.changes.subscribe(() => r++); r.should.equal(0); k.value = {id: 'john', age: 26}; r.should.equal(0); // --> no changes s.value = [{id: 'john', age: 26}, {id: 'jill', age: 27}]; r.should.equal(1); }); it('should emit once containing the initial additions for the initial value of the state', (done) => { let s = new KeyedDeep(new State([{id: 'john', age: 23}, {id: 'jack', age: 24}]), (_) => _.id); s.changes.subscribe((changes: ChangeMap) => { changes.additions.should.have.deep.members([ { index: '0', item: {id: 'john', age: 23}}, { index: '1', item: {id: 'jack', age: 24}}, ]); done(); }); }); it('should emit the initial change map with `initial` set to true and false afterwards.', (done) => { let s = new KeyedDeep(new State([{id: 'john', age: 23}, {id: 'jack', age: 24}]), (_) => _.id); let r = 0; s.changes.subscribe((changes: ChangeMap) => { if (r == 0) changes.initial.should.be.true; else changes.initial.should.be.false; r++; if (r == 3) done(); }); s.value = [{id: 'joe', age: 47}]; s.value = [{id: 'jill', age: 51}]; }); it('should emit for subsequent additions to the indices of the state.', (done) => { let s = new KeyedDeep(new State([{id: 'john', age: 23}, {id: 'jack', age: 24}]), (_) => _.id); s.bind(); // --> preventing the initial state to be considered changes s.changes.subscribe((changes: ChangeMap) => { changes.additions.should.have.deep.members([{ index: '2', item: { id: 'jill', age: 27 } }]); done(); }); s.value = s.value.concat([{id: 'jill', age: 27}]); }); it('should emit deletions from the indices of the state.', (done) => { let s = new KeyedDeep(new State([{id: 'john', age: 23}, {id: 'jack', age: 24}]), (_) => _.id); s.bind(); // --> preventing the initial state to be considered changes s.changes.subscribe((changes: ChangeMap) => { changes.deletions.should.have.deep.members([ { index: '0', item: {id: 'john', age: 23} } ]); done(); }); s.value = s.value.filter((i: any) => i.id != 'john'); }); it('should emit moving of indices of the state.', (done) => { let s = new KeyedDeep(new State([{id: 'john', age: 23}, {id: 'jack', age: 24}]), (_) => _.id); s.bind(); // --> preventing the initial state to be considered changes s.changes.subscribe((changes: ChangeMap) => { changes.moves.should.have.deep.members([{ oldIndex: '0', newIndex: '1', item: {id: 'john', age: 23} }, { oldIndex: '1', newIndex: '0', item: {id: 'jack', age: 24} }]); done(); }); s.value = [{id: 'jack', age: 24}, {id: 'john', age: 23}]; }); it('should emit moving of indices of the state as a result of deletions.', (done) => { let s = new KeyedDeep(new State([{id: 'john', age: 23}, {id: 'jack', age: 24}]), (_) => _.id); s.bind(); // --> preventing the initial state to be considered changes s.changes.subscribe((changes: ChangeMap) => { changes.moves.should.have.deep.members([{ oldIndex: '1', newIndex: '0', item: {id: 'jack', age: 24} }]); done(); }); s.value = s.value.filter((i: any) => i.id != 'john'); }); it('should emit moving of indices of the state as a result of additions.', (done) => { let s = new KeyedDeep(new State([{id: 'john', age: 23}]), (_) => _.id); s.bind(); // --> preventing the initial state to be considered changes s.changes.subscribe((changes: ChangeMap) => { changes.moves.should.have.deep.members([{ oldIndex: '0', newIndex: '1', item: {id: 'john', age: 23} }]); done(); }); s.value = [{id: 'jack', age: 24}].concat(s.value); }); it('should be possible to first subscribe on `.changes` and then on the state', () => { let s = new KeyedDeep(new State([]), _ => _.id); s.changes.subscribe(); s.subscribe(); }); }); });
the_stack
module dragonBones { /** * @class dragonBones.FastSlotTimelineState * @classdesc * FastSlotTimelineState 负责计算 Slot 的时间轴动画。 * FastSlotTimelineState 实例隶属于 FastAnimationState. FastAnimationState在创建时会为每个包含动作的 Slot生成一个 FastSlotTimelineState 实例. * @see dragonBones.FastAnimation * @see dragonBones.FastAnimationState * @see dragonBones.FastSlot */ export class FastSlotTimelineState{ private static HALF_PI:number = Math.PI * 0.5; private static DOUBLE_PI:number = Math.PI * 2; private static _pool:Array<FastSlotTimelineState> = []; /** @private */ public static borrowObject():FastSlotTimelineState{ if(FastSlotTimelineState._pool.length == 0){ return new FastSlotTimelineState(); } return FastSlotTimelineState._pool.pop(); } /** @private */ public static returnObject(timeline:FastSlotTimelineState):void{ if(FastSlotTimelineState._pool.indexOf(timeline) < 0){ FastSlotTimelineState._pool[FastSlotTimelineState._pool.length] = timeline; } timeline.clear(); } /** @private */ public static clear():void{ var i:number = FastSlotTimelineState._pool.length; while(i --){ FastSlotTimelineState._pool[i].clear(); } FastSlotTimelineState._pool.length = 0; } public name:string; /** @private */ public _weight:number; //TO DO 干什么用的 /** @private */ public _blendEnabled:boolean; /** @private */ public _isComplete:boolean; /** @private */ public _animationState:FastAnimationState; private _totalTime:number = 0; //duration private _currentTime:number = 0; private _currentFrameIndex:number = 0; private _currentFramePosition:number = 0; private _currentFrameDuration:number = 0; private _tweenEasing:number; private _tweenCurve:CurveData; private _tweenColor:boolean; private _colorChanged:boolean; //-1: frameLength>1, 0:frameLength==0, 1:frameLength==1 private _updateMode:number = 0; private _armature:FastArmature; private _animation:FastAnimation; private _slot:FastSlot; private _timelineData:SlotTimeline; private _durationColor:ColorTransform; public constructor(){ this._durationColor = new ColorTransform(); } private clear():void{ this._slot = null; this._armature = null; this._animation = null; this._animationState = null; this._timelineData = null; } //动画开始结束 /** @private */ public fadeIn(slot:FastSlot, animationState:FastAnimationState, timelineData:SlotTimeline):void{ this._slot = slot; this._armature = this._slot.armature; this._animation = this._armature.animation; this._animationState = animationState; this._timelineData = timelineData; this.name = timelineData.name; this._totalTime = this._timelineData.duration; this._isComplete = false; this._blendEnabled = false; this._tweenColor = false; this._currentFrameIndex = -1; this._currentTime = -1; this._tweenEasing = NaN; this._weight = 1; switch(this._timelineData.frameList.length){ case 0: this._updateMode = 0; break; case 1: this._updateMode = 1; break; default: this._updateMode = -1; break; } } //动画进行中 /** @private */ public updateFade(progress:number):void{ } /** @private */ public update(progress:number):void{ if(this._updateMode == -1){ this.updateMultipleFrame(progress); } else if(this._updateMode == 1){ this._updateMode = 0; this.updateSingleFrame(); } } private updateMultipleFrame(progress:number):void{ var currentPlayTimes:number = 0; progress /= this._timelineData.scale; progress += this._timelineData.offset; var currentTime:number = this._totalTime * progress; var playTimes:number = this._animationState.playTimes; if(playTimes == 0){ this._isComplete = false; currentPlayTimes = Math.ceil(Math.abs(currentTime) / this._totalTime) || 1; currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime; if(currentTime < 0){ currentTime += this._totalTime; } } else{ var totalTimes:number = playTimes * this._totalTime; if(currentTime >= totalTimes){ currentTime = totalTimes; this._isComplete = true; } else if(currentTime <= -totalTimes){ currentTime = -totalTimes; this._isComplete = true; } else{ this._isComplete = false; } if(currentTime < 0){ currentTime += totalTimes; } currentPlayTimes = Math.ceil(currentTime / this._totalTime) || 1; if(this._isComplete){ currentTime = this._totalTime; } else{ currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime; } } if(this._currentTime != currentTime){ this._currentTime = currentTime; var frameList:Array<Frame> = this._timelineData.frameList; var prevFrame:SlotFrame; var currentFrame:SlotFrame; for (var i:number = 0, l:number = this._timelineData.frameList.length; i < l; ++i){ if(this._currentFrameIndex < 0){ this._currentFrameIndex = 0; } else if(this._currentTime < this._currentFramePosition || this._currentTime >= this._currentFramePosition + this._currentFrameDuration){ this._currentFrameIndex ++; if(this._currentFrameIndex >= frameList.length){ if(this._isComplete){ this._currentFrameIndex --; break; } else{ this._currentFrameIndex = 0; } } } else{ break; } currentFrame = <SlotFrame><any> (frameList[this._currentFrameIndex]); if(prevFrame){ this._slot._arriveAtFrame(prevFrame, this._animationState); } this._currentFrameDuration = currentFrame.duration; this._currentFramePosition = currentFrame.position; prevFrame = currentFrame; } if(currentFrame){ this._slot._arriveAtFrame(currentFrame, this._animationState); this._blendEnabled = currentFrame.displayIndex >= 0; if(this._blendEnabled){ this.updateToNextFrame(currentPlayTimes); } else{ this._tweenEasing = NaN; this._tweenColor = false; } } if(this._blendEnabled){ this.updateTween(); } } } private updateToNextFrame(currentPlayTimes:number = 0):void{ var nextFrameIndex:number = this._currentFrameIndex + 1; if(nextFrameIndex >= this._timelineData.frameList.length){ nextFrameIndex = 0; } var currentFrame:SlotFrame = <SlotFrame><any> (this._timelineData.frameList[this._currentFrameIndex]); var nextFrame:SlotFrame = <SlotFrame><any> (this._timelineData.frameList[nextFrameIndex]); var tweenEnabled:boolean = false; if( nextFrameIndex == 0 && ( this._animationState.playTimes && this._animationState.currentPlayTimes >= this._animationState.playTimes && ((this._currentFramePosition + this._currentFrameDuration) / this._totalTime + currentPlayTimes - this._timelineData.offset) * this._timelineData.scale > 0.999999 ) ){ this._tweenEasing = NaN; tweenEnabled = false; } else if(currentFrame.displayIndex < 0 || nextFrame.displayIndex < 0){ this._tweenEasing = NaN; tweenEnabled = false; } else if(this._animationState.autoTween){ this._tweenEasing = this._animationState.animationData.tweenEasing; if(isNaN(this._tweenEasing)){ this._tweenEasing = currentFrame.tweenEasing; this._tweenCurve = currentFrame.curve; if(isNaN(this._tweenEasing) && this._tweenCurve == null) //frame no tween { tweenEnabled = false; } else{ if(this._tweenEasing == 10){ this._tweenEasing = 0; } //_tweenEasing [-1, 0) 0 (0, 1] (1, 2] tweenEnabled = true; } } else //animationData overwrite tween { //_tweenEasing [-1, 0) 0 (0, 1] (1, 2] tweenEnabled = true; } } else{ this._tweenEasing = currentFrame.tweenEasing; this._tweenCurve = currentFrame.curve; if((isNaN(this._tweenEasing) || this._tweenEasing == 10) && this._tweenCurve == null) //frame no tween { this._tweenEasing = NaN; tweenEnabled = false; } else{ //_tweenEasing [-1, 0) 0 (0, 1] (1, 2] tweenEnabled = true; } } if(tweenEnabled){ if(currentFrame.color || nextFrame.color){ ColorTransformUtil.minus(nextFrame.color || ColorTransformUtil.originalColor, currentFrame.color ||ColorTransformUtil.originalColor, this._durationColor); this._tweenColor = this._durationColor.alphaOffset != 0 || this._durationColor.redOffset != 0 || this._durationColor.greenOffset != 0 || this._durationColor.blueOffset != 0 || this._durationColor.alphaMultiplier != 0 || this._durationColor.redMultiplier != 0 || this._durationColor.greenMultiplier != 0 || this._durationColor.blueMultiplier != 0; } else{ this._tweenColor = false; } } else{ this._tweenColor = false; } if(!this._tweenColor){ var targetColor:ColorTransform; var colorChanged:boolean; if(currentFrame.color){ targetColor = currentFrame.color; colorChanged = true; } else{ targetColor = ColorTransformUtil.originalColor; colorChanged = false; } if ((this._slot._isColorChanged || colorChanged)){ if( !ColorTransformUtil.isEqual(this._slot._colorTransform, targetColor)){ this._slot._updateDisplayColor( targetColor.alphaOffset, targetColor.redOffset, targetColor.greenOffset, targetColor.blueOffset, targetColor.alphaMultiplier, targetColor.redMultiplier, targetColor.greenMultiplier, targetColor.blueMultiplier, colorChanged ); } } } } private updateTween():void{ var currentFrame:SlotFrame = <SlotFrame><any> (this._timelineData.frameList[this._currentFrameIndex]); if(this._tweenColor){ var progress:number = (this._currentTime - this._currentFramePosition) / this._currentFrameDuration; if (this._tweenCurve != null){ progress = this._tweenCurve.getValueByProgress(progress); } else if(this._tweenEasing){ progress = MathUtil.getEaseValue(progress, this._tweenEasing); } if(currentFrame.color){ this._slot._updateDisplayColor( currentFrame.color.alphaOffset + this._durationColor.alphaOffset * progress, currentFrame.color.redOffset + this._durationColor.redOffset * progress, currentFrame.color.greenOffset + this._durationColor.greenOffset * progress, currentFrame.color.blueOffset + this._durationColor.blueOffset * progress, currentFrame.color.alphaMultiplier + this._durationColor.alphaMultiplier * progress, currentFrame.color.redMultiplier + this._durationColor.redMultiplier * progress, currentFrame.color.greenMultiplier + this._durationColor.greenMultiplier * progress, currentFrame.color.blueMultiplier + this._durationColor.blueMultiplier * progress, true ); } else{ this._slot._updateDisplayColor( this._durationColor.alphaOffset * progress, this._durationColor.redOffset * progress, this._durationColor.greenOffset * progress, this._durationColor.blueOffset * progress, this._durationColor.alphaMultiplier * progress + 1, this._durationColor.redMultiplier * progress + 1, this._durationColor.greenMultiplier * progress + 1, this._durationColor.blueMultiplier * progress + 1, true ); } } } private updateSingleFrame():void{ var currentFrame:SlotFrame = <SlotFrame><any> (this._timelineData.frameList[0]); this._slot._arriveAtFrame(currentFrame, this._animationState); this._isComplete = true; this._tweenEasing = NaN; this._tweenColor = false; this._blendEnabled = currentFrame.displayIndex >= 0; if(this._blendEnabled){ var targetColor:ColorTransform; var colorChanged:boolean; if(currentFrame.color){ targetColor = currentFrame.color; colorChanged = true; } else{ targetColor = ColorTransformUtil.originalColor; colorChanged = false; } if ((this._slot._isColorChanged || colorChanged)){ if( !ColorTransformUtil.isEqual(this._slot._colorTransform, targetColor)){ this._slot._updateDisplayColor( targetColor.alphaOffset, targetColor.redOffset, targetColor.greenOffset, targetColor.blueOffset, targetColor.alphaMultiplier, targetColor.redMultiplier, targetColor.greenMultiplier, targetColor.blueMultiplier, colorChanged ); } } } } } }
the_stack
import { token } from '../token' import { Storage, PrimType, t_bool, t_u8, t_i8, t_u16, t_i16, t_u32, t_i32, t_u64, t_i64, t_uintptr, t_f32, t_f64, } from "../ast" import { Op } from './op' import { ops } from "./ops" // opselect1 returns the IR operation for the corresponding token operator // and operand type. // export function opselect1(tok :token, x :PrimType) :Op { switch (tok) { case token.NOT: return ops.Not case token.SUB: switch (x.storage) { // -arg case Storage.i8: return ops.NegI8 case Storage.i16: return ops.NegI16 case Storage.i32: return ops.NegI32 case Storage.i64: return ops.NegI64 case Storage.i32: return ops.NegF32 case Storage.i64: return ops.NegF64 }; break } // switch // unhandled operator token assert(false, `invalid token.${token[tok]} with type ${x}`) return ops.Invalid } // opselect2 returns the IR operator for the corresponding token operator // and operand types. // export function opselect2(tok :token, x :PrimType, y :PrimType) :Op { switch (tok) { // // arithmetic // case token.ADD: switch (x.storage) { // + case Storage.i8: return ops.AddI8 case Storage.i16: return ops.AddI16 case Storage.i32: return ops.AddI32 case Storage.i64: return ops.AddI64 case Storage.f32: return ops.AddF32 case Storage.f64: return ops.AddF64 }; break case token.SUB: switch (x.storage) { // - case Storage.i8: return ops.SubI8 case Storage.i16: return ops.SubI16 case Storage.i32: return ops.SubI32 case Storage.i64: return ops.SubI64 case Storage.f32: return ops.SubF32 case Storage.f64: return ops.SubF64 }; break case token.MUL: switch (x.storage) { // * case Storage.i8: return ops.MulI8 case Storage.i16: return ops.MulI16 case Storage.i32: return ops.MulI32 case Storage.i64: return ops.MulI64 case Storage.f32: return ops.MulF32 case Storage.f64: return ops.MulF64 }; break case token.QUO: switch (x) { // / case t_i8: return ops.DivS8 case t_u8: return ops.DivU8 case t_i16: return ops.DivS16 case t_u16: return ops.DivU16 case t_i32: return ops.DivS32 case t_u32: return ops.DivU32 case t_i64: return ops.DivS64 case t_u64: return ops.DivU64 case t_f32: return ops.DivF32 case t_f64: return ops.DivF64 }; break case token.REM: switch (x) { // % case t_i8: return ops.RemS8 case t_u8: return ops.RemU8 case t_i16: return ops.RemS16 case t_u16: return ops.RemU16 case t_i32: return ops.RemS32 case t_u32: return ops.RemU32 case t_i64: return ops.RemI64 case t_u64: return ops.RemU64 }; break case token.AND: switch (x.storage) { // & case Storage.i8: return ops.AndI8 case Storage.i16: return ops.AndI16 case Storage.i32: return ops.AndI32 case Storage.i64: return ops.AndI64 }; break case token.OR: switch (x.storage) { // | case Storage.i8: return ops.OrI8 case Storage.i16: return ops.OrI16 case Storage.i32: return ops.OrI32 case Storage.i64: return ops.OrI64 }; break case token.XOR: switch (x.storage) { // ^ case Storage.i8: return ops.XorI8 case Storage.i16: return ops.XorI16 case Storage.i32: return ops.XorI32 case Storage.i64: return ops.XorI64 }; break case token.AND_NOT: // &^ TODO implement. Emulated by: x & ~y assert(false, 'AND_NOT "&^" not yet supported') break // // comparisons // case token.EQL: switch (x.storage) { // == case Storage.i8: return ops.EqI8 case Storage.i16: return ops.EqI16 case Storage.i32: return ops.EqI32 case Storage.i64: return ops.EqI64 case Storage.f32: return ops.EqF32 case Storage.f64: return ops.EqF64 }; break case token.NEQ: switch (x.storage) { // != case Storage.i8: return ops.NeqI8 case Storage.i16: return ops.NeqI16 case Storage.i32: return ops.NeqI32 case Storage.i64: return ops.NeqI64 case Storage.f32: return ops.NeqF32 case Storage.f64: return ops.NeqF64 }; break case token.LSS: switch (x) { // < case t_i8: return ops.LessS8 case t_u8: return ops.LessU8 case t_i16: return ops.LessS16 case t_u16: return ops.LessU16 case t_i32: return ops.LessS32 case t_u32: return ops.LessU32 case t_i64: return ops.LessS64 case t_u64: return ops.LessU64 case t_f32: return ops.LessF32 case t_f64: return ops.LessF64 }; break case token.LEQ: switch (x) { // <= case t_i8: return ops.LeqS8 case t_u8: return ops.LeqU8 case t_i16: return ops.LeqS16 case t_u16: return ops.LeqU16 case t_i32: return ops.LeqS32 case t_u32: return ops.LeqU32 case t_i64: return ops.LeqS64 case t_u64: return ops.LeqU64 case t_f32: return ops.LeqF32 case t_f64: return ops.LeqF64 }; break case token.GTR: switch (x) { // > case t_i8: return ops.GreaterS8 case t_u8: return ops.GreaterU8 case t_i16: return ops.GreaterS16 case t_u16: return ops.GreaterU16 case t_i32: return ops.GreaterS32 case t_u32: return ops.GreaterU32 case t_i64: return ops.GreaterS64 case t_u64: return ops.GreaterU64 case t_f32: return ops.GreaterF32 case t_f64: return ops.GreaterF64 }; break case token.GEQ: switch (x) { // >= case t_i8: return ops.GeqS8 case t_u8: return ops.GeqU8 case t_i16: return ops.GeqS16 case t_u16: return ops.GeqU16 case t_i32: return ops.GeqS32 case t_u32: return ops.GeqU32 case t_i64: return ops.GeqS64 case t_u64: return ops.GeqU64 case t_f32: return ops.GeqF32 case t_f64: return ops.GeqF64 }; break // // shifts // case token.SHL: switch (x.storage) { // << case Storage.i8: switch (y) { case t_u8: return ops.ShLI8x8 case t_u16: return ops.ShLI8x16 case t_u32: return ops.ShLI8x32 case t_u64: return ops.ShLI8x64 } break case Storage.i16: switch (y) { case t_u8: return ops.ShLI16x8 case t_u16: return ops.ShLI16x16 case t_u32: return ops.ShLI16x32 case t_u64: return ops.ShLI16x64 } break case Storage.i32: switch (y) { case t_u8: return ops.ShLI32x8 case t_u16: return ops.ShLI32x16 case t_u32: return ops.ShLI32x32 case t_u64: return ops.ShLI32x64 } break case Storage.i64: switch (y) { case t_u8: return ops.ShLI64x8 case t_u16: return ops.ShLI64x16 case t_u32: return ops.ShLI64x32 case t_u64: return ops.ShLI64x64 } break }; break case token.SHR: assert(y.isUIntType()); switch (x) { // >> case t_i8: switch (y) { case t_u8: return ops.ShRS8x8 case t_u16: return ops.ShRS8x16 case t_u32: return ops.ShRS8x32 case t_u64: return ops.ShRS8x64 } break case t_u8: switch (y) { case t_u8: return ops.ShRU8x8 case t_u16: return ops.ShRU8x16 case t_u32: return ops.ShRU8x32 case t_u64: return ops.ShRU8x64 } break case t_i16: switch (y) { case t_u8: return ops.ShRS16x8 case t_u16: return ops.ShRS16x16 case t_u32: return ops.ShRS16x32 case t_u64: return ops.ShRS16x64 } break case t_u16: switch (y) { case t_u8: return ops.ShRU16x8 case t_u16: return ops.ShRU16x16 case t_u32: return ops.ShRU16x32 case t_u64: return ops.ShRU16x64 } break case t_i32: switch (y) { case t_u8: return ops.ShRS32x8 case t_u16: return ops.ShRS32x16 case t_u32: return ops.ShRS32x32 case t_u64: return ops.ShRS32x64 } break case t_u32: switch (y) { case t_u8: return ops.ShRU32x8 case t_u16: return ops.ShRU32x16 case t_u32: return ops.ShRU32x32 case t_u64: return ops.ShRU32x64 } break case t_i64: switch (y) { case t_u8: return ops.ShRS64x8 case t_u16: return ops.ShRS64x16 case t_u32: return ops.ShRS64x32 case t_u64: return ops.ShRS64x64 } break case t_u64: switch (y) { case t_u8: return ops.ShRU64x8 case t_u16: return ops.ShRU64x16 case t_u32: return ops.ShRU64x32 case t_u64: return ops.ShRU64x64 } break }; break } // switch // unhandled operator token assert(false, `invalid token.${token[tok]} with types ${x}, ${y}`) return ops.Invalid } // opselectConv returns the IR operation for converting x to y. // export function opselectConv(src :PrimType, dst :PrimType) :Op { switch (src) { case t_i8: switch (dst) { case t_bool: return ops.TruncI8toBool case t_i16: return ops.SignExtI8to16 case t_i32: return ops.SignExtI8to32 case t_i64: return ops.SignExtI8to64 }; break case t_u8: switch (dst) { case t_bool: return ops.TruncI8toBool case t_u16: return ops.ZeroExtI8to16 case t_u32: return ops.ZeroExtI8to32 case t_u64: return ops.ZeroExtI8to64 }; break case t_i16: switch (dst) { case t_bool: return ops.TruncI16toBool case t_i8: return ops.TruncI16to8 case t_i32: return ops.SignExtI16to32 case t_i64: return ops.SignExtI16to64 }; break case t_u16: switch (dst) { case t_bool: return ops.TruncI16toBool case t_u8: return ops.TruncI16to8 case t_u32: return ops.ZeroExtI16to32 case t_u64: return ops.ZeroExtI16to64 }; break case t_i32: switch (dst) { case t_bool: return ops.TruncI32toBool case t_i8: return ops.TruncI32to8 case t_i16: return ops.TruncI32to16 case t_i64: return ops.SignExtI32to64 case t_f32: return ops.ConvI32toF32 case t_f64: return ops.ConvI32toF64 }; break case t_u32: switch (dst) { case t_bool: return ops.TruncI32toBool case t_u8: return ops.TruncI32to8 case t_u16: return ops.TruncI32to16 case t_u64: return ops.ZeroExtI32to64 case t_f32: return ops.ConvU32toF32 case t_f64: return ops.ConvU32toF64 }; break case t_i64: switch (dst) { case t_bool: return ops.TruncI64toBool case t_i8: return ops.TruncI64to8 case t_i16: return ops.TruncI64to16 case t_i32: return ops.TruncI64to32 case t_f32: return ops.ConvI64toF32 case t_f64: return ops.ConvI64toF64 }; break case t_u64: switch (dst) { case t_bool: return ops.TruncI64toBool case t_u8: return ops.TruncI64to8 case t_u16: return ops.TruncI64to16 case t_u32: return ops.TruncI64to32 case t_f32: return ops.ConvU64toF32 case t_f64: return ops.ConvU64toF64 }; break case t_f32: switch (dst) { case t_bool: return ops.TruncF32toBool case t_i32: return ops.ConvF32toI32 case t_u32: return ops.ConvF32toU32 case t_i64: return ops.ConvF32toI64 case t_u64: return ops.ConvF32toU64 case t_f64: return ops.ConvF32toF64 }; break case t_f64: switch (dst) { case t_bool: return ops.TruncF64toBool case t_i32: return ops.ConvF64toI32 case t_u32: return ops.ConvF64toU32 case t_i64: return ops.ConvF64toI64 case t_u64: return ops.ConvF64toU64 case t_f32: return ops.ConvF64toF32 }; break } // switch // unhandled operator token assert(false, `invalid conversion ${src} -> ${dst}`) return ops.Invalid }
the_stack
import { TsFileImageDimensionConstraints } from './image-dimension-constraints'; import { TsFileAcceptedMimeTypes } from './mime-types'; import { TsSelectedFile } from './selected-file'; const CONSTRAINTS_MOCK: TsFileImageDimensionConstraints = [ { height: { min: 50, max: 100, }, width: { min: 50, max: 100, }, }, { height: { min: 100, max: 100, }, width: { min: 100, max: 100, }, }, ]; // IMAGE MOCK const FILE_BLOB = new Blob( // eslint-disable-next-line max-len ['data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABIAQMAAABvIyEEAAAAA1BMVEXXbFn0Q9OUAAAADklEQVR4AWMYRmAUjAIAAtAAAaW+yXMAAAAASUVORK5CYII='], { type: 'image/png' }, ); FILE_BLOB['lastModifiedDate'] = new Date(); FILE_BLOB['name'] = 'foo'; jest.spyOn(FILE_BLOB, 'size', 'get').mockReturnValue(3 * 1024); const FILE_MOCK = FILE_BLOB as File; // CSV MOCK const FILE_CSV_BLOB = new Blob( ['my csv value'], { type: 'text/csv' }, ); FILE_CSV_BLOB['lastModifiedDate'] = new Date(); FILE_CSV_BLOB['name'] = 'myCSV'; jest.spyOn(FILE_CSV_BLOB, 'size', 'get').mockReturnValue(3 * 1024); const FILE_CSV_MOCK = FILE_CSV_BLOB as File; // VIDEO MOCK const FILE_VIDEO_BLOB = new Blob( ['my video value'], { type: 'video/mp4' }, ); FILE_VIDEO_BLOB['lastModifiedDate'] = new Date(); FILE_VIDEO_BLOB['name'] = 'myVideo'; jest.spyOn(FILE_VIDEO_BLOB, 'size', 'get').mockReturnValue(3 * 1024); const FILE_VIDEO_MOCK = FILE_VIDEO_BLOB as File; describe(`TsSelectedFile`, function() { const createFile = ( file = FILE_MOCK, constraints: TsFileImageDimensionConstraints | undefined = CONSTRAINTS_MOCK, types: TsFileAcceptedMimeTypes[] = ['image/png', 'image/jpg'], size = (10 * 1024), ratio = [{ widthRatio: 1, heightRatio: 1, }], ): TsSelectedFile => new TsSelectedFile( file, constraints ? constraints : undefined, types, size, ratio, ); // Mock `FileReader` and `Image`: beforeEach(() => { // Mock FileReader class DummyFileReader { public onload = jest.fn(); public addEventListener = jest.fn(); public readAsDataURL = jest.fn().mockImplementation(function(this: FileReader) { // FIXME // @ts-ignore this.onload({} as Event); }); // eslint-disable-next-line max-len public result = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABIAQMAAABvIyEEAAAAA1BMVEXXbFn0Q9OUAAAADklEQVR4AWMYRmAUjAIAAtAAAaW+yXMAAAAASUVORK5CYII='; } // Not sure why any is needed (window as any).FileReader = jest.fn(() => new DummyFileReader); class DummyImage { public _onload = () => {}; public set onload(fn) { this._onload = fn; } public get onload() { return this._onload; } public set src(source) { this.onload(); } public get naturalWidth() { return 100; } public get naturalHeight() { return 100; } } (window as any).Image = jest.fn(() => new DummyImage()); }); describe(`constructor`, () => { test(`should set top-level items and validations`, () => { const file = createFile(); file.fileLoaded$.subscribe(f => { if (f) { expect(f.mimeType).toEqual('image/png'); expect(f.size).toEqual(3); expect(f.name).toEqual('foo'); expect(f.validations.fileType).toEqual(true); expect(f.validations.fileSize).toEqual(true); expect(f.validations.imageDimensions).toEqual(true); } }); expect.assertions(6); }); test(`should set top-level items and validations for videos`, done => { const file = createFile(FILE_VIDEO_MOCK, undefined, ['video/mp4']); file.fileLoaded$.subscribe(f => { if (f) { expect(f.mimeType).toEqual('video/mp4'); expect(f.size).toEqual(3); expect(f.name).toEqual('myVideo'); expect(f.validations.fileType).toEqual(true); expect(f.validations.fileSize).toEqual(true); expect(f.validations.imageDimensions).toEqual(true); } }); expect.assertions(6); done(); }); }); describe(`width`, () => { test(`should return the width or zero`, () => { const file = createFile(); expect(file.width).toEqual(100); file.dimensions = undefined; expect(file.width).toEqual(0); }); }); describe(`height`, () => { test(`should return the height or zero`, () => { const file = createFile(); expect(file.height).toEqual(100); file.dimensions = undefined; expect(file.height).toEqual(0); }); }); describe(`isCSV`, () => { test(`should return true is the file is a CSV`, () => { const file = createFile(FILE_CSV_MOCK); file.fileLoaded$.subscribe(f => { if (f) { expect(f.isCSV).toEqual(true); } }); expect.assertions(1); }); }); describe(`isImage`, () => { test(`should return true is the file is an image`, () => { const file = createFile(); file.fileLoaded$.subscribe(f => { if (f) { expect(file.isImage).toEqual(true); } }); }); }); describe(`isVideo`, () => { test(`should return true is the file is a video`, () => { const file = createFile(FILE_VIDEO_MOCK); file.fileLoaded$.subscribe(f => { if (f) { expect(f.isVideo).toEqual(true); } }); expect.assertions(1); }); }); describe(`fileContents`, () => { test(`should return the FileReader result`, () => { const file = createFile(); file.fileLoaded$.subscribe(f => { if (f) { expect(f.fileContents.indexOf('data:image')).toBeGreaterThanOrEqual(0); } }); expect.assertions(1); }); describe(`fileReader result`, () => { /** * Convert a string to an array buffer * * @param str */ function str2ab(str) { const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char const bufView = new Uint16Array(buf); for (let i = 0, strLen = str.length; i < strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; } test(`should warn if image result is not a string`, () => { window.console.warn = jest.fn(); // Mock FileReader for ArrayBuffer class DummyArrayBufferFileReader { public onload = jest.fn(); public addEventListener = jest.fn(); public readAsDataURL = jest.fn().mockImplementation(function(this: FileReader) { // FIXME // @ts-ignore this.onload!({} as ProgressEvent); }); public result = str2ab(FILE_BLOB); } (window as any).FileReader = jest.fn(() => new DummyArrayBufferFileReader); const file = createFile(); file.fileLoaded$.subscribe(f => {}); expect(window.console.warn).toHaveBeenCalled(); expect.assertions(1); }); test(`should warn if csv result is not a string`, () => { window.console.warn = jest.fn(); // Mock FileReader for ArrayBuffer class DummyArrayBufferFileReader { public onload = jest.fn(); public addEventListener = jest.fn(); public readAsDataURL = jest.fn().mockImplementation(function(this: FileReader) { // FIXME // @ts-ignore this.onload!({} as ProgressEvent); }); public result = str2ab(FILE_CSV_BLOB); } (window as any).FileReader = jest.fn(() => new DummyArrayBufferFileReader); const file = createFile(FILE_CSV_MOCK); file.fileLoaded$.subscribe(f => { file.fileContents.valueOf(); }); expect(window.console.warn).toHaveBeenCalled(); expect.assertions(1); }); }); }); describe(`isValid`, () => { const file = createFile(); beforeEach(() => { file.validations.fileType = true; file.validations.fileSize = true; file.validations.imageDimensions = true; file.validations.imageRatio = true; }); test(`should return true if all validations are true`, () => { expect(file.isValid).toEqual(true); }); test(`should return false if file type validation is false`, () => { file.validations.fileType = false; expect(file.isValid).toEqual(false); }); test(`should return false if file size validation is false`, () => { file.validations.fileSize = false; expect(file.isValid).toEqual(false); }); test(`should return false if image dimensions validation is false`, () => { file.validations.imageDimensions = false; expect(file.isValid).toEqual(false); }); test(`should return false if image ration validation is false`, () => { file.validations.imageRatio = false; expect(file.isValid).toEqual(false); }); }); describe(`determineImageDimensions`, () => { test(`should set validation to true and exit if the file is not an image`, done => { const file = createFile(FILE_CSV_MOCK); file.fileLoaded$.subscribe(f => { if (f) { expect(f.dimensions).toBeFalsy(); expect(f.height).toEqual(0); expect(f.width).toEqual(0); expect(f.validations.imageDimensions).toEqual(true); done(); } }); expect.assertions(4); }); test(`should still seed the FileReader for non-image files`, done => { const file = createFile(FILE_CSV_MOCK); file.fileLoaded$.subscribe(f => { if (f) { expect(f.fileContents).toBeTruthy(); done(); } }); expect.assertions(1); }); test(`should set dimensions and call callback`, () => { createFile().fileLoaded$.subscribe(f => { if (f) { expect(f.dimensions).toBeTruthy(); expect(f.height).toBeGreaterThan(1); expect(f.width).toBeGreaterThan(1); expect(f.validations.imageDimensions).toEqual(true); } }); expect.assertions(4); }); }); describe(`validateImageRatio`, () => { test(`should return true if no constraints exist`, () => { const file = createFile(); expect(file['validateImageRatio'](undefined)).toEqual(true); }); test(`should return true if ratio are valid`, () => { const file = createFile(); const result = file['validateImageRatio']([{ widthRatio: 1, heightRatio: 1, }]); expect(result).toEqual(true); }); test(`should return false if ratio are not valid`, () => { const file = createFile(); const result = file['validateImageRatio']([{ widthRatio: 2, heightRatio: 1, }]); expect(result).toEqual(false); }); }); describe(`validateImageDimensions`, () => { test(`should return true if no constraints exist`, () => { const file = createFile(); expect(file['validateImageDimensions'](undefined)).toEqual(true); }); test(`should return true if dimensions are valid`, () => { const file = createFile(); const result = file['validateImageDimensions'](CONSTRAINTS_MOCK); expect(result).toEqual(true); }); test(`should return false if dimensions are not valid`, () => { const file = createFile(); const constraints = [ { height: { min: 150, max: 200, }, width: { min: 150, max: 200, }, }, { height: { min: 100, max: 100, }, width: { min: 150, max: 200, }, }, ]; const result = file['validateImageDimensions'](constraints); expect(result).toEqual(false); }); }); });
the_stack
import SubscriptionQos from "../../../../main/js/joynr/proxy/SubscriptionQos"; import PeriodicSubscriptionQos from "../../../../main/js/joynr/proxy/PeriodicSubscriptionQos"; import OnChangeSubscriptionQos from "../../../../main/js/joynr/proxy/OnChangeSubscriptionQos"; import OnChangeWithKeepAliveSubscriptionQos from "../../../../main/js/joynr/proxy/OnChangeWithKeepAliveSubscriptionQos"; import MulticastSubscriptionQos from "../../../../main/js/joynr/proxy/MulticastSubscriptionQos"; import * as UtilInternal from "../../../../main/js/joynr/util/UtilInternal"; describe("libjoynr-js.joynr.proxy.SubscriptionQos", () => { const qosSettings = { minIntervalMs: 50, maxIntervalMs: 51, expiryDateMs: 4, alertAfterIntervalMs: 80, publicationTtlMs: 100 }; it("is instantiable", done => { expect(new OnChangeWithKeepAliveSubscriptionQos(qosSettings)).toBeDefined(); done(); }); it("is of correct type", done => { const subscriptionQos = new OnChangeWithKeepAliveSubscriptionQos(qosSettings); expect(subscriptionQos).toBeDefined(); expect(subscriptionQos).not.toBeNull(); expect(typeof subscriptionQos === "object").toBeTruthy(); expect(subscriptionQos instanceof OnChangeWithKeepAliveSubscriptionQos).toEqual(true); done(); }); // compare existing member values of subscriptionQos to the corresponding ones in expectedOutput function compareSubscriptionQosSettings(subscriptionQos: any, expectedOutput: any, specification?: any) { // fields expiryDateMs and publicationTtlMs should exist in any case expect(subscriptionQos.expiryDateMs).toEqual(expectedOutput.expiryDateMs); expect(subscriptionQos.publicationTtlMs).toEqual(expectedOutput.publicationTtlMs); switch (specification) { case "PeriodicSubscriptionQos": // Do we have a PeriodicSubscriptionQos object? => fields periodMs and alertAfterIntervalMs should exist expect(subscriptionQos.periodMs).toEqual(expectedOutput.periodMs); expect(subscriptionQos.alertAfterIntervalMs).toEqual(expectedOutput.periodicAlertAfterIntervalMs); break; case "OnChangeWithKeepAliveSubscriptionQos": // Do we have an OnChangeWithKeepAliveSubscriptionQos object? => fields min- and maxIntervalMs and alertAfterIntervalMs should exist expect(subscriptionQos.maxIntervalMs).toEqual(expectedOutput.maxIntervalMs); expect(subscriptionQos.alertAfterIntervalMs).toEqual(expectedOutput.onChangeAlertAfterIntervalMs); // fall through case "OnChangeSubscriptionQos": // Do we have an OnChangeSubscriptionQos object? => field minIntervalMs should exist expect(subscriptionQos.minIntervalMs).toEqual(expectedOutput.minIntervalMs); break; default: // no further fields to check break; } } // for each input: Call constructors of SubscriptionQos and every subclass and check output function checkSettingsInSubscriptionQosAndChildren(input: any, expectedOutput: any) { // check if SubscriptionQos is constructed with correct member values compareSubscriptionQosSettings( new SubscriptionQos({ expiryDateMs: input.expiryDateMs, publicationTtlMs: input.publicationTtlMs }), expectedOutput ); compareSubscriptionQosSettings(new MulticastSubscriptionQos(input), expectedOutput); compareSubscriptionQosSettings( new PeriodicSubscriptionQos({ expiryDateMs: input.expiryDateMs, alertAfterIntervalMs: input.periodicAlertAfterIntervalMs, publicationTtlMs: input.publicationTtlMs, periodMs: input.periodMs }), expectedOutput, "PeriodicSubscriptionQos" ); compareSubscriptionQosSettings(new OnChangeSubscriptionQos(input), expectedOutput, "OnChangeSubscriptionQos"); compareSubscriptionQosSettings( new OnChangeWithKeepAliveSubscriptionQos({ minIntervalMs: input.minIntervalMs, maxIntervalMs: input.maxIntervalMs, expiryDateMs: input.expiryDateMs, alertAfterIntervalMs: input.onChangeAlertAfterIntervalMs, publicationTtlMs: input.publicationTtlMs }), expectedOutput, "OnChangeWithKeepAliveSubscriptionQos" ); } const defaultTestSettings = { expiryDateMs: 4, publicationTtlMs: 150, periodMs: 55, periodicAlertAfterIntervalMs: 80, minIntervalMs: 5, maxIntervalMs: 60, onChangeAlertAfterIntervalMs: 1000 }; // add non-existing keys in settings function addDefaultKeys(settings: any) { if (settings.expiryDateMs === undefined) { settings.expiryDateMs = defaultTestSettings.expiryDateMs; } if (settings.publicationTtlMs === undefined) { settings.publicationTtlMs = defaultTestSettings.publicationTtlMs; } if (settings.periodMs === undefined) { settings.periodMs = defaultTestSettings.periodMs; } if (settings.periodicAlertAfterIntervalMs === undefined) { settings.periodicAlertAfterIntervalMs = defaultTestSettings.periodicAlertAfterIntervalMs; } if (settings.minIntervalMs === undefined) { settings.minIntervalMs = defaultTestSettings.minIntervalMs; } if (settings.maxIntervalMs === undefined) { settings.maxIntervalMs = defaultTestSettings.maxIntervalMs; } if (settings.onChangeAlertAfterIntervalMs === undefined) { settings.onChangeAlertAfterIntervalMs = defaultTestSettings.onChangeAlertAfterIntervalMs; } return settings; } it("constructs SubscriptionQos (and subclasses) with correct member values", done => { // all values regular (lower limits) { const input = { expiryDateMs: SubscriptionQos.MIN_EXPIRY_MS, publicationTtlMs: SubscriptionQos.MIN_PUBLICATION_TTL_MS, periodMs: PeriodicSubscriptionQos.MIN_PERIOD_MS, periodicAlertAfterIntervalMs: PeriodicSubscriptionQos.MIN_PERIOD_MS, minIntervalMs: OnChangeSubscriptionQos.MIN_MIN_INTERVAL_MS, maxIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MIN_MAX_INTERVAL_MS, onChangeAlertAfterIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MIN_MAX_INTERVAL_MS }; const expectedOutput = { expiryDateMs: SubscriptionQos.MIN_EXPIRY_MS, publicationTtlMs: SubscriptionQos.MIN_PUBLICATION_TTL_MS, periodMs: PeriodicSubscriptionQos.MIN_PERIOD_MS, periodicAlertAfterIntervalMs: PeriodicSubscriptionQos.MIN_PERIOD_MS, minIntervalMs: OnChangeSubscriptionQos.MIN_MIN_INTERVAL_MS, maxIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MIN_MAX_INTERVAL_MS, onChangeAlertAfterIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MIN_MAX_INTERVAL_MS }; checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // all values regular (random values) { const input = addDefaultKeys({}); const expectedOutput = addDefaultKeys({}); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // all values regular (upper limits) { const input = { expiryDateMs: UtilInternal.getMaxLongValue(), publicationTtlMs: SubscriptionQos.MAX_PUBLICATION_TTL_MS, periodMs: PeriodicSubscriptionQos.MAX_PERIOD_MS, periodicAlertAfterIntervalMs: PeriodicSubscriptionQos.MAX_ALERT_AFTER_INTERVAL_MS, minIntervalMs: OnChangeSubscriptionQos.MAX_MIN_INTERVAL_MS, maxIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MAX_MAX_INTERVAL_MS, onChangeAlertAfterIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MAX_ALERT_AFTER_INTERVAL_MS }; const expectedOutput = { expiryDateMs: UtilInternal.getMaxLongValue(), publicationTtlMs: SubscriptionQos.MAX_PUBLICATION_TTL_MS, periodMs: PeriodicSubscriptionQos.MAX_PERIOD_MS, periodicAlertAfterIntervalMs: PeriodicSubscriptionQos.MAX_ALERT_AFTER_INTERVAL_MS, minIntervalMs: OnChangeSubscriptionQos.MAX_MIN_INTERVAL_MS, maxIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MAX_MAX_INTERVAL_MS, onChangeAlertAfterIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MAX_ALERT_AFTER_INTERVAL_MS }; checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // publicationTtlMs < SubscriptionQos.MIN_PUBLICATION_TTL_MS { const input = addDefaultKeys({ publicationTtlMs: SubscriptionQos.MIN_PUBLICATION_TTL_MS - 1 }); const expectedOutput = addDefaultKeys({ publicationTtlMs: SubscriptionQos.MIN_PUBLICATION_TTL_MS }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // publicationTtlMs > SubscriptionQos.MAX_PUBLICATION_TTL_MS { const input = addDefaultKeys({ publicationTtlMs: SubscriptionQos.MAX_PUBLICATION_TTL_MS + 1 }); const expectedOutput = addDefaultKeys({ publicationTtlMs: SubscriptionQos.MAX_PUBLICATION_TTL_MS }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // expiryDateMs < SubscriptionQos.MIN_EXPIRY_MS { const input = addDefaultKeys({ expiryDateMs: SubscriptionQos.MIN_EXPIRY_MS - 1 }); const expectedOutput = addDefaultKeys({ expiryDateMs: SubscriptionQos.MIN_EXPIRY_MS }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // periodMs < PeriodicSubscriptionQos.MIN_PERIOD_MS expect(() => { // eslint-disable-next-line no-new new PeriodicSubscriptionQos(addDefaultKeys({ periodMs: PeriodicSubscriptionQos.MIN_PERIOD_MS - 1 })); }).toThrow(); // periodMs > PeriodicSubscriptionQos.MAX_PERIOD_MS expect(() => { // eslint-disable-next-line no-new new PeriodicSubscriptionQos(addDefaultKeys({ periodMs: PeriodicSubscriptionQos.MAX_PERIOD_MS + 1 })); }).toThrow(); // PeriodicSubscriptionQos.alertAfterIntervalMs !== PeriodicSubscriptionQos.NO_ALERT_AFTER_INTERVAL && PeriodicSubscriptionQos.alertAfterIntervalMs < periodMs { const input = addDefaultKeys({ periodicAlertAfterIntervalMs: 2999, periodMs: 3000 }); const expectedOutput = addDefaultKeys({ periodicAlertAfterIntervalMs: 3000, periodMs: 3000 }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // PeriodicSubscriptionQos.alertAfterIntervalMs === PeriodicSubscriptionQos.NO_ALERT_AFTER_INTERVAL && PeriodicSubscriptionQos.alertAfterIntervalMs < periodMs { const input = addDefaultKeys({ periodicAlertAfterIntervalMs: PeriodicSubscriptionQos.NO_ALERT_AFTER_INTERVAL, periodMs: PeriodicSubscriptionQos.NO_ALERT_AFTER_INTERVAL + 50 }); const expectedOutput = addDefaultKeys({ periodicAlertAfterIntervalMs: PeriodicSubscriptionQos.NO_ALERT_AFTER_INTERVAL, periodMs: PeriodicSubscriptionQos.NO_ALERT_AFTER_INTERVAL + 50 }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // PeriodicSubscriptionQos.alertAfterIntervalMs > PeriodicSubscriptionQos.MAX_ALERT_AFTER_INTERVAL_MS { const input = addDefaultKeys({ periodicAlertAfterIntervalMs: PeriodicSubscriptionQos.MAX_ALERT_AFTER_INTERVAL_MS + 1 }); const expectedOutput = addDefaultKeys({ periodicAlertAfterIntervalMs: PeriodicSubscriptionQos.MAX_ALERT_AFTER_INTERVAL_MS }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // minIntervalMs < OnChangeSubscriptionQos.MIN_MIN_INTERVAL_MS { const input = addDefaultKeys({ minIntervalMs: OnChangeSubscriptionQos.MIN_MIN_INTERVAL_MS - 1 }); const expectedOutput = addDefaultKeys({ minIntervalMs: OnChangeSubscriptionQos.MIN_MIN_INTERVAL_MS }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // minIntervalMs > OnChangeSubscriptionQos.MAX_MIN_INTERVAL_MS { const input = addDefaultKeys({ minIntervalMs: OnChangeSubscriptionQos.MAX_MIN_INTERVAL_MS + 1, maxIntervalMs: OnChangeSubscriptionQos.MAX_MIN_INTERVAL_MS, onChangeAlertAfterIntervalMs: OnChangeSubscriptionQos.MAX_MIN_INTERVAL_MS }); const expectedOutput = addDefaultKeys({ minIntervalMs: OnChangeSubscriptionQos.MAX_MIN_INTERVAL_MS, maxIntervalMs: OnChangeSubscriptionQos.MAX_MIN_INTERVAL_MS, onChangeAlertAfterIntervalMs: OnChangeSubscriptionQos.MAX_MIN_INTERVAL_MS }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // maxIntervalMs < OnChangeWithKeepAliveSubscriptionQos.MIN_MAX_INTERVAL_MS { const input = addDefaultKeys({ maxIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MIN_MAX_INTERVAL_MS - 1 }); const expectedOutput = addDefaultKeys({ maxIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MIN_MAX_INTERVAL_MS }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // maxIntervalMs > OnChangeWithKeepAliveSubscriptionQos.MAX_MAX_INTERVAL_MS { const input = addDefaultKeys({ maxIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MAX_MAX_INTERVAL_MS + 1, onChangeAlertAfterIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MAX_MAX_INTERVAL_MS }); const expectedOutput = addDefaultKeys({ maxIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MAX_MAX_INTERVAL_MS, onChangeAlertAfterIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MAX_MAX_INTERVAL_MS }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // maxIntervalMs < minIntervalMs { const input = addDefaultKeys({ maxIntervalMs: 200, minIntervalMs: 500 }); const expectedOutput = addDefaultKeys({ maxIntervalMs: 500, minIntervalMs: 500 }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // OnChangeWithKeepAliveSubscriptionQos.alertAfterIntervalMs !== OnChangeWithKeepAliveSubscriptionQos.NO_ALERT_AFTER_INTERVAL // && OnChangeWithKeepAliveSubscriptionQos.alertAfterIntervalMs < maxIntervalMs { const input = addDefaultKeys({ maxIntervalMs: 4000, onChangeAlertAfterIntervalMs: 2000 }); const expectedOutput = addDefaultKeys({ maxIntervalMs: 4000, onChangeAlertAfterIntervalMs: 4000 }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // OnChangeWithKeepAliveSubscriptionQos.alertAfterIntervalMs === OnChangeWithKeepAliveSubscriptionQos.NO_ALERT_AFTER_INTERVAL // && OnChangeWithKeepAliveSubscriptionQos.alertAfterIntervalMs < maxIntervalMs { const input = addDefaultKeys({ maxIntervalMs: OnChangeWithKeepAliveSubscriptionQos.NO_ALERT_AFTER_INTERVAL + 100, onChangeAlertAfterIntervalMs: OnChangeWithKeepAliveSubscriptionQos.NO_ALERT_AFTER_INTERVAL }); const expectedOutput = addDefaultKeys({ maxIntervalMs: OnChangeWithKeepAliveSubscriptionQos.NO_ALERT_AFTER_INTERVAL + 100, onChangeAlertAfterIntervalMs: OnChangeWithKeepAliveSubscriptionQos.NO_ALERT_AFTER_INTERVAL }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } // OnChangeWithKeepAliveSubscriptionQos.alertAfterIntervalMs > OnChangeWithKeepAliveSubscriptionQos.MAX_ALERT_AFTER_INTERVAL_MS { const input = addDefaultKeys({ onChangeAlertAfterIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MAX_ALERT_AFTER_INTERVAL_MS + 1 }); const expectedOutput = addDefaultKeys({ onChangeAlertAfterIntervalMs: OnChangeWithKeepAliveSubscriptionQos.MAX_ALERT_AFTER_INTERVAL_MS }); checkSettingsInSubscriptionQosAndChildren(input, expectedOutput); } done(); }); it("constructs SubscriptionQos with correct default values", done => { const fixture = new SubscriptionQos(); expect(fixture.expiryDateMs).toEqual(SubscriptionQos.NO_EXPIRY_DATE); expect(fixture.publicationTtlMs).toEqual(SubscriptionQos.DEFAULT_PUBLICATION_TTL_MS); done(); }); it("constructs MulticastSubscriptionQos with correct default values", done => { const fixture = new MulticastSubscriptionQos(); expect(fixture.expiryDateMs).toEqual(SubscriptionQos.NO_EXPIRY_DATE); expect(fixture.publicationTtlMs).toEqual(SubscriptionQos.DEFAULT_PUBLICATION_TTL_MS); done(); }); it("constructs PeriodicSubscriptionQos with correct default values", done => { const fixture = new PeriodicSubscriptionQos(); expect(fixture.periodMs).toEqual(PeriodicSubscriptionQos.DEFAULT_PERIOD_MS); expect(fixture.expiryDateMs).toEqual(SubscriptionQos.NO_EXPIRY_DATE); expect(fixture.alertAfterIntervalMs).toEqual(PeriodicSubscriptionQos.DEFAULT_ALERT_AFTER_INTERVAL_MS); expect(fixture.publicationTtlMs).toEqual(SubscriptionQos.DEFAULT_PUBLICATION_TTL_MS); done(); }); it("constructs OnChangeSubscriptionQos with correct default values", done => { const fixture = new OnChangeSubscriptionQos(); expect(fixture.expiryDateMs).toEqual(SubscriptionQos.NO_EXPIRY_DATE); expect(fixture.publicationTtlMs).toEqual(SubscriptionQos.DEFAULT_PUBLICATION_TTL_MS); expect(fixture.minIntervalMs).toEqual(OnChangeSubscriptionQos.DEFAULT_MIN_INTERVAL_MS); done(); }); it("constructs OnChangeWithKeepAliveSubscriptionQos with correct default values", done => { const fixture = new OnChangeWithKeepAliveSubscriptionQos(); expect(fixture.minIntervalMs).toEqual(OnChangeSubscriptionQos.DEFAULT_MIN_INTERVAL_MS); expect(fixture.maxIntervalMs).toEqual(OnChangeWithKeepAliveSubscriptionQos.DEFAULT_MAX_INTERVAL_MS); expect(fixture.expiryDateMs).toEqual(SubscriptionQos.NO_EXPIRY_DATE); expect(fixture.alertAfterIntervalMs).toEqual( OnChangeWithKeepAliveSubscriptionQos.DEFAULT_ALERT_AFTER_INTERVAL_MS ); expect(fixture.publicationTtlMs).toEqual(SubscriptionQos.DEFAULT_PUBLICATION_TTL_MS); done(); }); it("SubscriptionQos.clearExpiryDate clears the expiry date", done => { const fixture = new OnChangeWithKeepAliveSubscriptionQos({ expiryDateMs: 1234 }); expect(fixture.expiryDateMs).toBe(1234); fixture.clearExpiryDate(); expect(fixture.expiryDateMs).toBe(SubscriptionQos.NO_EXPIRY_DATE); done(); }); it("PeriodicSubscriptionQos.clearAlertAfterInterval clears the alert after interval", done => { const alertAfterIntervalMs = PeriodicSubscriptionQos.DEFAULT_PERIOD_MS + 1; const fixture = new PeriodicSubscriptionQos({ alertAfterIntervalMs }); expect(fixture.alertAfterIntervalMs).toBe(alertAfterIntervalMs); fixture.clearAlertAfterInterval(); expect(fixture.alertAfterIntervalMs).toBe(PeriodicSubscriptionQos.NO_ALERT_AFTER_INTERVAL); done(); }); it("OnChangeWithKeepAliveSubscriptionQos.clearAlertAfterInterval clears the alert after interval", done => { const alertAfterIntervalMs = OnChangeWithKeepAliveSubscriptionQos.DEFAULT_MAX_INTERVAL_MS + 1; const fixture = new OnChangeWithKeepAliveSubscriptionQos({ alertAfterIntervalMs }); expect(fixture.alertAfterIntervalMs).toBe(alertAfterIntervalMs); fixture.clearAlertAfterInterval(); expect(fixture.alertAfterIntervalMs).toBe(OnChangeWithKeepAliveSubscriptionQos.NO_ALERT_AFTER_INTERVAL); done(); }); it("subscription qos accepts validity instead of expiry date as constructor member", done => { const fakeTime = 374747473; const validityMs = 23232; jest.spyOn(Date, "now").mockImplementation(() => { return fakeTime; }); const fixture = new OnChangeWithKeepAliveSubscriptionQos({ validityMs }); expect(fixture.expiryDateMs).toBe(fakeTime + validityMs); done(); }); });
the_stack
import { ArchiveTag } from "../../../ComplexProperties/ArchiveTag"; import { ComplexPropertyDefinition } from "../../../PropertyDefinitions/ComplexPropertyDefinition"; import { EffectiveRightsPropertyDefinition } from "../../../PropertyDefinitions/EffectiveRightsPropertyDefinition"; import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion"; import { FolderId } from "../../../ComplexProperties/FolderId"; import { GenericPropertyDefinition } from "../../../PropertyDefinitions/GenericPropertyDefinition"; import { IntPropertyDefinition } from "../../../PropertyDefinitions/IntPropertyDefinition"; import { ManagedFolderInformation } from "../../../ComplexProperties/ManagedFolderInformation"; import { PermissionSetPropertyDefinition } from "../../../PropertyDefinitions/PermissionSetPropertyDefinition"; import { PolicyTag } from "../../../ComplexProperties/PolicyTag"; import { PropertyDefinition } from "../../../PropertyDefinitions/PropertyDefinition"; import { PropertyDefinitionFlags } from "../../../Enumerations/PropertyDefinitionFlags"; import { StringPropertyDefinition } from "../../../PropertyDefinitions/StringPropertyDefinition"; import { WellKnownFolderName } from "../../../Enumerations/WellKnownFolderName"; import { XmlElementNames } from "../../XmlElementNames"; import { ServiceObjectSchema } from "./ServiceObjectSchema"; /** * Field URIs for folders. */ module FieldUris { export var FolderId: string = "folder:FolderId"; export var ParentFolderId: string = "folder:ParentFolderId"; export var DisplayName: string = "folder:DisplayName"; export var UnreadCount: string = "folder:UnreadCount"; export var TotalCount: string = "folder:TotalCount"; export var ChildFolderCount: string = "folder:ChildFolderCount"; export var FolderClass: string = "folder:FolderClass"; export var ManagedFolderInformation: string = "folder:ManagedFolderInformation"; export var EffectiveRights: string = "folder:EffectiveRights"; export var PermissionSet: string = "folder:PermissionSet"; export var PolicyTag: string = "folder:PolicyTag"; export var ArchiveTag: string = "folder:ArchiveTag"; export var DistinguishedFolderId: string = "folder:DistinguishedFolderId"; } /** * Represents the schema for folders. */ export class FolderSchema extends ServiceObjectSchema { /** * Defines the **Id** property. */ public static Id: PropertyDefinition = new ComplexPropertyDefinition<FolderId>( "Id", XmlElementNames.FolderId, FieldUris.FolderId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new FolderId(); } ); /** * Defines the **FolderClass** property. */ public static FolderClass: PropertyDefinition = new StringPropertyDefinition( "FolderClass", XmlElementNames.FolderClass, FieldUris.FolderClass, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ParentFolderId** property. */ public static ParentFolderId: PropertyDefinition = new ComplexPropertyDefinition<FolderId>( "ParentFolderId", XmlElementNames.ParentFolderId, FieldUris.ParentFolderId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new FolderId(); } ); /** * Defines the **ChildFolderCount** property. */ public static ChildFolderCount: PropertyDefinition = new IntPropertyDefinition( "ChildFolderCount", XmlElementNames.ChildFolderCount, FieldUris.ChildFolderCount, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **DisplayName** property. */ public static DisplayName: PropertyDefinition = new StringPropertyDefinition( "DisplayName", XmlElementNames.DisplayName, FieldUris.DisplayName, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **UnreadCount** property. */ public static UnreadCount: PropertyDefinition = new IntPropertyDefinition( "UnreadCount", XmlElementNames.UnreadCount, FieldUris.UnreadCount, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **TotalCount** property. */ public static TotalCount: PropertyDefinition = new IntPropertyDefinition( "TotalCount", XmlElementNames.TotalCount, FieldUris.TotalCount, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ManagedFolderInformation** property. */ public static ManagedFolderInformation: PropertyDefinition = new ComplexPropertyDefinition<ManagedFolderInformation>( "ManagedFolderInformation", XmlElementNames.ManagedFolderInformation, FieldUris.ManagedFolderInformation, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new ManagedFolderInformation(); } ); /** * Defines the **EffectiveRights** property. */ public static EffectiveRights: PropertyDefinition = new EffectiveRightsPropertyDefinition( "EffectiveRights", XmlElementNames.EffectiveRights, FieldUris.EffectiveRights, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Permissions** property. */ public static Permissions: PropertyDefinition = new PermissionSetPropertyDefinition( "Permissions", XmlElementNames.PermissionSet, FieldUris.PermissionSet, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.MustBeExplicitlyLoaded, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **WellKnownFolderName** property. */ public static WellKnownFolderName: PropertyDefinition = new GenericPropertyDefinition<WellKnownFolderName>( "WellKnownFolderName", XmlElementNames.DistinguishedFolderId, FieldUris.DistinguishedFolderId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, WellKnownFolderName ); /** * Defines the **PolicyTag** property. */ public static PolicyTag: PropertyDefinition = new ComplexPropertyDefinition<PolicyTag>( "PolicyTag", XmlElementNames.PolicyTag, FieldUris.PolicyTag, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, () => { return new PolicyTag(); } ); /** * Defines the **ArchiveTag** property. */ public static ArchiveTag: PropertyDefinition = new ComplexPropertyDefinition<ArchiveTag>( "ArchiveTag", XmlElementNames.ArchiveTag, FieldUris.ArchiveTag, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, () => { return new ArchiveTag(); } ); /** * @internal Instance of **FolderSchema** */ static Instance: FolderSchema = new FolderSchema(); /** * Registers properties. * * /remarks/ IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd) */ RegisterProperties(): void { super.RegisterProperties(); this.RegisterProperty(FolderSchema, FolderSchema.Id); this.RegisterProperty(FolderSchema, FolderSchema.ParentFolderId); this.RegisterProperty(FolderSchema, FolderSchema.FolderClass); this.RegisterProperty(FolderSchema, FolderSchema.DisplayName); this.RegisterProperty(FolderSchema, FolderSchema.TotalCount); this.RegisterProperty(FolderSchema, FolderSchema.ChildFolderCount); this.RegisterProperty(FolderSchema, ServiceObjectSchema.ExtendedProperties); this.RegisterProperty(FolderSchema, FolderSchema.ManagedFolderInformation); this.RegisterProperty(FolderSchema, FolderSchema.EffectiveRights); this.RegisterProperty(FolderSchema, FolderSchema.Permissions); this.RegisterProperty(FolderSchema, FolderSchema.UnreadCount); this.RegisterProperty(FolderSchema, FolderSchema.WellKnownFolderName); this.RegisterProperty(FolderSchema, FolderSchema.PolicyTag); this.RegisterProperty(FolderSchema, FolderSchema.ArchiveTag); } } /** * Represents the schema for folders. */ export interface FolderSchema { /** * Defines the **Id** property. */ Id: PropertyDefinition; /** * Defines the **FolderClass** property. */ FolderClass: PropertyDefinition; /** * Defines the **ParentFolderId** property. */ ParentFolderId: PropertyDefinition; /** * Defines the **ChildFolderCount** property. */ ChildFolderCount: PropertyDefinition; /** * Defines the **DisplayName** property. */ DisplayName: PropertyDefinition; /** * Defines the **UnreadCount** property. */ UnreadCount: PropertyDefinition; /** * Defines the **TotalCount** property. */ TotalCount: PropertyDefinition; /** * Defines the **ManagedFolderInformation** property. */ ManagedFolderInformation: PropertyDefinition; /** * Defines the **EffectiveRights** property. */ EffectiveRights: PropertyDefinition; /** * Defines the **Permissions** property. */ Permissions: PropertyDefinition; /** * Defines the **WellKnownFolderName** property. */ WellKnownFolderName: PropertyDefinition; /** * Defines the **PolicyTag** property. */ PolicyTag: PropertyDefinition; /** * Defines the **ArchiveTag** property. */ ArchiveTag: PropertyDefinition; /** * @internal Instance of **FolderSchema** */ Instance: FolderSchema; } /** * Represents the schema for folders. */ export interface FolderSchemaStatic extends FolderSchema { }
the_stack
import { Duration, Names, Resource } from '@aws-cdk/core'; import { Construct } from 'constructs'; import { CfnResponseHeadersPolicy } from './cloudfront.generated'; /** * Represents a response headers policy. */ export interface IResponseHeadersPolicy { /** * The ID of the response headers policy * @attribute **/ readonly responseHeadersPolicyId: string; } /** * Properties for creating a Response Headers Policy */ export interface ResponseHeadersPolicyProps { /** * A unique name to identify the response headers policy. * * @default - generated from the `id` */ readonly responseHeadersPolicyName?: string; /** * A comment to describe the response headers policy. * * @default - no comment */ readonly comment?: string; /** * A configuration for a set of HTTP response headers that are used for cross-origin resource sharing (CORS). * * @default - no cors behavior */ readonly corsBehavior?: ResponseHeadersCorsBehavior; /** * A configuration for a set of custom HTTP response headers. * * @default - no custom headers behavior */ readonly customHeadersBehavior?: ResponseCustomHeadersBehavior; /** * A configuration for a set of security-related HTTP response headers. * * @default - no security headers behavior */ readonly securityHeadersBehavior?: ResponseSecurityHeadersBehavior; } /** * A Response Headers Policy configuration * * @resource AWS::CloudFront::ResponseHeadersPolicy */ export class ResponseHeadersPolicy extends Resource implements IResponseHeadersPolicy { /** Use this managed policy to allow simple CORS requests from any origin. */ public static readonly CORS_ALLOW_ALL_ORIGINS = ResponseHeadersPolicy.fromManagedResponseHeadersPolicy('60669652-455b-4ae9-85a4-c4c02393f86c'); /** Use this managed policy to allow CORS requests from any origin, including preflight requests. */ public static readonly CORS_ALLOW_ALL_ORIGINS_WITH_PREFLIGHT = ResponseHeadersPolicy.fromManagedResponseHeadersPolicy('5cc3b908-e619-4b99-88e5-2cf7f45965bd'); /** Use this managed policy to add a set of security headers to all responses that CloudFront sends to viewers. */ public static readonly SECURITY_HEADERS = ResponseHeadersPolicy.fromManagedResponseHeadersPolicy('67f7725c-6f97-4210-82d7-5512b31e9d03'); /** Use this managed policy to allow simple CORS requests from any origin and add a set of security headers to all responses that CloudFront sends to viewers. */ public static readonly CORS_ALLOW_ALL_ORIGINS_AND_SECURITY_HEADERS = ResponseHeadersPolicy.fromManagedResponseHeadersPolicy('e61eb60c-9c35-4d20-a928-2b84e02af89c'); /** Use this managed policy to allow CORS requests from any origin, including preflight requests, and add a set of security headers to all responses that CloudFront sends to viewers. */ public static readonly CORS_ALLOW_ALL_ORIGINS_WITH_PREFLIGHT_AND_SECURITY_HEADERS = ResponseHeadersPolicy.fromManagedResponseHeadersPolicy('eaab4381-ed33-4a86-88ca-d9558dc6cd63'); /** * Import an existing Response Headers Policy from its ID. */ public static fromResponseHeadersPolicyId(scope: Construct, id: string, responseHeadersPolicyId: string): IResponseHeadersPolicy { class Import extends Resource implements IResponseHeadersPolicy { public readonly responseHeadersPolicyId = responseHeadersPolicyId; } return new Import(scope, id); } private static fromManagedResponseHeadersPolicy(managedResponseHeadersPolicyId: string): IResponseHeadersPolicy { return new class implements IResponseHeadersPolicy { public readonly responseHeadersPolicyId = managedResponseHeadersPolicyId; }; } public readonly responseHeadersPolicyId: string; constructor(scope: Construct, id: string, props: ResponseHeadersPolicyProps = {}) { super(scope, id, { physicalName: props.responseHeadersPolicyName, }); const responseHeadersPolicyName = props.responseHeadersPolicyName ?? Names.uniqueId(this); const resource = new CfnResponseHeadersPolicy(this, 'Resource', { responseHeadersPolicyConfig: { name: responseHeadersPolicyName, comment: props.comment, corsConfig: props.corsBehavior ? this._renderCorsConfig(props.corsBehavior) : undefined, customHeadersConfig: props.customHeadersBehavior ? this._renderCustomHeadersConfig(props.customHeadersBehavior) : undefined, securityHeadersConfig: props.securityHeadersBehavior ? this._renderSecurityHeadersConfig(props.securityHeadersBehavior) : undefined, }, }); this.responseHeadersPolicyId = resource.ref; } private _renderCorsConfig(behavior: ResponseHeadersCorsBehavior): CfnResponseHeadersPolicy.CorsConfigProperty { return { accessControlAllowCredentials: behavior.accessControlAllowCredentials, accessControlAllowHeaders: { items: behavior.accessControlAllowHeaders }, accessControlAllowMethods: { items: behavior.accessControlAllowMethods }, accessControlAllowOrigins: { items: behavior.accessControlAllowOrigins }, accessControlExposeHeaders: behavior.accessControlExposeHeaders ? { items: behavior.accessControlExposeHeaders } : undefined, accessControlMaxAgeSec: behavior.accessControlMaxAge ? behavior.accessControlMaxAge.toSeconds() : undefined, originOverride: behavior.originOverride, }; } private _renderCustomHeadersConfig(behavior: ResponseCustomHeadersBehavior): CfnResponseHeadersPolicy.CustomHeadersConfigProperty { return { items: behavior.customHeaders, }; } private _renderSecurityHeadersConfig(behavior: ResponseSecurityHeadersBehavior): CfnResponseHeadersPolicy.SecurityHeadersConfigProperty { return { contentSecurityPolicy: behavior.contentSecurityPolicy, contentTypeOptions: behavior.contentTypeOptions, frameOptions: behavior.frameOptions, referrerPolicy: behavior.referrerPolicy, strictTransportSecurity: behavior.strictTransportSecurity ? { ...behavior.strictTransportSecurity, accessControlMaxAgeSec: behavior.strictTransportSecurity.accessControlMaxAge.toSeconds(), }: undefined, xssProtection: behavior.xssProtection, }; } } /** * Configuration for a set of HTTP response headers that are used for cross-origin resource sharing (CORS). * CloudFront adds these headers to HTTP responses that it sends for CORS requests that match a cache behavior * associated with this response headers policy. */ export interface ResponseHeadersCorsBehavior { /** * A Boolean that CloudFront uses as the value for the Access-Control-Allow-Credentials HTTP response header. */ readonly accessControlAllowCredentials: boolean; /** * A list of HTTP header names that CloudFront includes as values for the Access-Control-Allow-Headers HTTP response header. * You can specify `['*']` to allow all headers. */ readonly accessControlAllowHeaders: string[]; /** * A list of HTTP methods that CloudFront includes as values for the Access-Control-Allow-Methods HTTP response header. */ readonly accessControlAllowMethods: string[]; /** * A list of origins (domain names) that CloudFront can use as the value for the Access-Control-Allow-Origin HTTP response header. * You can specify `['*']` to allow all origins. */ readonly accessControlAllowOrigins: string[]; /** * A list of HTTP headers that CloudFront includes as values for the Access-Control-Expose-Headers HTTP response header. * You can specify `['*']` to expose all headers. * * @default - no headers exposed */ readonly accessControlExposeHeaders?: string[]; /** * A number that CloudFront uses as the value for the Access-Control-Max-Age HTTP response header. * * @default - no max age */ readonly accessControlMaxAge?: Duration; /** * A Boolean that determines whether CloudFront overrides HTTP response headers received from the origin with the ones specified in this response headers policy. */ readonly originOverride: boolean; } /** * Configuration for a set of HTTP response headers that are sent for requests that match a cache behavior * that’s associated with this response headers policy. */ export interface ResponseCustomHeadersBehavior { /** * The list of HTTP response headers and their values. */ readonly customHeaders: ResponseCustomHeader[]; } /** * An HTTP response header name and its value. * CloudFront includes this header in HTTP responses that it sends for requests that match a cache behavior that’s associated with this response headers policy. */ export interface ResponseCustomHeader { /** * The HTTP response header name. */ readonly header: string; /** * A Boolean that determines whether CloudFront overrides a response header with the same name * received from the origin with the header specified here. */ readonly override: boolean; /** * The value for the HTTP response header. */ readonly value: string; } /** * Configuration for a set of security-related HTTP response headers. * CloudFront adds these headers to HTTP responses that it sends for requests that match a cache behavior * associated with this response headers policy. */ export interface ResponseSecurityHeadersBehavior { /** * The policy directives and their values that CloudFront includes as values for the Content-Security-Policy HTTP response header. * * @default - no content security policy */ readonly contentSecurityPolicy?: ResponseHeadersContentSecurityPolicy; /** * Determines whether CloudFront includes the X-Content-Type-Options HTTP response header with its value set to nosniff. * * @default - no content type options */ readonly contentTypeOptions?: ResponseHeadersContentTypeOptions; /** * Determines whether CloudFront includes the X-Frame-Options HTTP response header and the header’s value. * * @default - no frame options */ readonly frameOptions?: ResponseHeadersFrameOptions; /** * Determines whether CloudFront includes the Referrer-Policy HTTP response header and the header’s value. * * @default - no referrer policy */ readonly referrerPolicy?: ResponseHeadersReferrerPolicy; /** * Determines whether CloudFront includes the Strict-Transport-Security HTTP response header and the header’s value. * * @default - no strict transport security */ readonly strictTransportSecurity?: ResponseHeadersStrictTransportSecurity; /** * Determines whether CloudFront includes the X-XSS-Protection HTTP response header and the header’s value. * * @default - no xss protection */ readonly xssProtection?: ResponseHeadersXSSProtection; } /** * The policy directives and their values that CloudFront includes as values for the Content-Security-Policy HTTP response header. */ export interface ResponseHeadersContentSecurityPolicy { /** * The policy directives and their values that CloudFront includes as values for the Content-Security-Policy HTTP response header. */ readonly contentSecurityPolicy: string; /** * A Boolean that determines whether CloudFront overrides the Content-Security-Policy HTTP response header * received from the origin with the one specified in this response headers policy. */ readonly override: boolean; } /** * Determines whether CloudFront includes the X-Content-Type-Options HTTP response header with its value set to nosniff. */ export interface ResponseHeadersContentTypeOptions { /** * A Boolean that determines whether CloudFront overrides the X-Content-Type-Options HTTP response header * received from the origin with the one specified in this response headers policy. */ readonly override: boolean; } /** * Determines whether CloudFront includes the X-Frame-Options HTTP response header and the header’s value. */ export interface ResponseHeadersFrameOptions { /** * The value of the X-Frame-Options HTTP response header. */ readonly frameOption: HeadersFrameOption; /** * A Boolean that determines whether CloudFront overrides the X-Frame-Options HTTP response header * received from the origin with the one specified in this response headers policy. */ readonly override: boolean; } /** * Determines whether CloudFront includes the Referrer-Policy HTTP response header and the header’s value. */ export interface ResponseHeadersReferrerPolicy { /** * The value of the Referrer-Policy HTTP response header. */ readonly referrerPolicy: HeadersReferrerPolicy; /** * A Boolean that determines whether CloudFront overrides the Referrer-Policy HTTP response header * received from the origin with the one specified in this response headers policy. */ readonly override: boolean; } /** * Determines whether CloudFront includes the Strict-Transport-Security HTTP response header and the header’s value. */ export interface ResponseHeadersStrictTransportSecurity { /** * A number that CloudFront uses as the value for the max-age directive in the Strict-Transport-Security HTTP response header. */ readonly accessControlMaxAge: Duration; /** * A Boolean that determines whether CloudFront includes the includeSubDomains directive in the Strict-Transport-Security HTTP response header. * * @default false */ readonly includeSubdomains?: boolean; /** * A Boolean that determines whether CloudFront overrides the Strict-Transport-Security HTTP response header * received from the origin with the one specified in this response headers policy. */ readonly override: boolean; /** * A Boolean that determines whether CloudFront includes the preload directive in the Strict-Transport-Security HTTP response header. * * @default false */ readonly preload?: boolean; } /** * Determines whether CloudFront includes the X-XSS-Protection HTTP response header and the header’s value. */ export interface ResponseHeadersXSSProtection { /** * A Boolean that determines whether CloudFront includes the mode=block directive in the X-XSS-Protection header. * * @default false */ readonly modeBlock?: boolean; /** * A Boolean that determines whether CloudFront overrides the X-XSS-Protection HTTP response header * received from the origin with the one specified in this response headers policy. */ readonly override: boolean; /** * A Boolean that determines the value of the X-XSS-Protection HTTP response header. * When this setting is true, the value of the X-XSS-Protection header is 1. * When this setting is false, the value of the X-XSS-Protection header is 0. */ readonly protection: boolean; /** * A reporting URI, which CloudFront uses as the value of the report directive in the X-XSS-Protection header. * You cannot specify a ReportUri when ModeBlock is true. * * @default - no report uri */ readonly reportUri?: string; } /** * Enum representing possible values of the X-Frame-Options HTTP response header. */ export enum HeadersFrameOption { /** * The page can only be displayed in a frame on the same origin as the page itself. */ DENY = 'DENY', /** * The page can only be displayed in a frame on the specified origin. */ SAMEORIGIN = 'SAMEORIGIN', } /** * Enum representing possible values of the Referrer-Policy HTTP response header. */ export enum HeadersReferrerPolicy { /** * The referrer policy is not set. */ NO_REFERRER = 'no-referrer', /** * The referrer policy is no-referrer-when-downgrade. */ NO_REFERRER_WHEN_DOWNGRADE = 'no-referrer-when-downgrade', /** * The referrer policy is origin. */ ORIGIN = 'origin', /** * The referrer policy is origin-when-cross-origin. */ ORIGIN_WHEN_CROSS_ORIGIN = 'origin-when-cross-origin', /** * The referrer policy is same-origin. */ SAME_ORIGIN = 'same-origin', /** * The referrer policy is strict-origin. */ STRICT_ORIGIN = 'strict-origin', /** * The referrer policy is strict-origin-when-cross-origin. */ STRICT_ORIGIN_WHEN_CROSS_ORIGIN = 'strict-origin-when-cross-origin', /** * The referrer policy is unsafe-url. */ UNSAFE_URL = 'unsafe-url', }
the_stack
import { assign, createMachine, createSchema, send, sendParent, StateSchema, } from "xstate"; import { log } from "xstate/lib/actions"; import { assert } from "@renproject/utils"; import { AcceptedGatewayTransaction, AllGatewayTransactions, ConfirmingGatewayTransaction, GatewayTransaction, isAccepted, isCompleted, isConfirming, isMinted, isSubmitted, MintedGatewayTransaction, SubmittingGatewayTransaction, } from "../types/mint"; type extractGeneric<Type> = Type extends AllGatewayTransactions<infer X> ? X : never; /** The context that the deposit machine acts on */ export interface DepositMachineContext< Deposit extends AllGatewayTransactions<extractGeneric<Deposit>>, > { /** The deposit being tracked */ deposit: Deposit; } const largest = (x?: number, y?: number): number => { if (!x) { if (y) return y; return 0; } if (!y) { if (x) return x; return 0; } if (x > y) return x; return y; }; export enum DepositStates { CHECKING_COMPLETION = "checkingCompletion", /** We are waiting for ren-js to find the deposit */ RESTORING_DEPOSIT = "restoringDeposit", /** We couldn't restore this deposit */ ERROR_RESTORING = "errorRestoring", /** renjs has found the deposit for the transaction */ RESTORED_DEPOSIT = "restoredDeposit", /** we are waiting for the source chain to confirm the transaction */ CONFIRMING_DEPOSIT = "srcSettling", /** source chain has confirmed the transaction, submitting to renvm for signature */ RENVM_SIGNING = "srcConfirmed", /** renvm has accepted and signed the transaction */ RENVM_ACCEPTED = "accepted", /** renvm did not accept the tx */ ERROR_SIGNING = "errorAccepting", /** the user is submitting the transaction to mint on the destination chain */ SUBMITTING_MINT = "claiming", /** there was an error submitting the tx to the destination chain */ ERROR_MINTING = "errorSubmitting", /** We have recieved a txHash for the destination chain */ MINTING = "destInitiated", /** user has acknowledged that the transaction is completed, so we can stop listening for further deposits */ COMPLETED = "completed", /** user does not want to mint this deposit or the transaction reverted */ REJECTED = "rejected", } export type DepositMachineTypestate<X> = | { value: DepositStates.CHECKING_COMPLETION; context: DepositMachineContext<AllGatewayTransactions<X>>; } | { value: DepositStates.RESTORING_DEPOSIT; context: DepositMachineContext<AllGatewayTransactions<X>>; } | { value: DepositStates.ERROR_RESTORING; context: DepositMachineContext<GatewayTransaction<X>>; } | { value: DepositStates.RESTORED_DEPOSIT; context: DepositMachineContext<GatewayTransaction<X>>; } | { value: DepositStates.CONFIRMING_DEPOSIT; context: DepositMachineContext<ConfirmingGatewayTransaction<X>>; } | { value: DepositStates.RENVM_SIGNING; context: DepositMachineContext<AcceptedGatewayTransaction<X>>; } | { value: DepositStates.RENVM_ACCEPTED; context: DepositMachineContext<AcceptedGatewayTransaction<X>>; } | { value: DepositStates.ERROR_SIGNING; context: DepositMachineContext<ConfirmingGatewayTransaction<X>>; } | { value: DepositStates.SUBMITTING_MINT; context: DepositMachineContext<SubmittingGatewayTransaction<X>>; } | { value: DepositStates.ERROR_MINTING; context: DepositMachineContext<SubmittingGatewayTransaction<X>>; } | { value: DepositStates.MINTING; context: DepositMachineContext<MintedGatewayTransaction<X>>; } | { value: DepositStates.COMPLETED; context: DepositMachineContext<MintedGatewayTransaction<X>>; } | { value: DepositStates.REJECTED; context: DepositMachineContext<GatewayTransaction<X>>; }; /** The states a deposit can be in */ export interface DepositMachineSchema<X> extends StateSchema<DepositMachineContext<AllGatewayTransactions<X>>> { states: { /** check if we can skip instantiating the deposit, if we finished the tx * previously */ checkingCompletion: {}; /** We are waiting for ren-js to find the deposit */ restoringDeposit: {}; /** We couldn't restore this deposit */ errorRestoring: {}; /** renjs has found the deposit for the transaction */ restoredDeposit: {}; /** we are waiting for the source chain to confirm the transaction */ srcSettling: {}; /** source chain has confirmed the transaction */ srcConfirmed: {}; /** renvm has accepted and signed the transaction */ accepted: {}; /** renvm did not accept the tx */ errorAccepting: {}; /** the user is submitting the transaction to mint on the destination chain */ claiming: {}; /** there was an error submitting the tx to the destination chain */ errorSubmitting: {}; /** We have recieved a txHash for the destination chain */ destInitiated: {}; /** user has acknowledged that the transaction is completed, so we can stop listening for further deposits */ completed: {}; /** user does not want to claim this deposit */ rejected: {}; }; } export interface ContractParams { [key: string]: any; } export type DepositMachineEvent<X> = | { type: "NOOP" } | { type: "CHECK" } | { type: "LISTENING" } | { type: "DETECTED" } | { type: "ERROR"; data: Partial<GatewayTransaction<X>>; error: Error } | { type: "RESTORE"; data: Partial<AllGatewayTransactions<X>> } | { type: "RESTORED"; data: AllGatewayTransactions<X> } | { type: "CONFIRMED"; data: Partial<ConfirmingGatewayTransaction<X>> } | { type: "CONFIRMATION"; data: Partial<ConfirmingGatewayTransaction<X>> } | { type: "SIGNED"; data: AcceptedGatewayTransaction<X> } | { type: "SIGN_ERROR"; data: GatewayTransaction<X>; error: Error } | { type: "REVERTED"; data: GatewayTransaction<X>; error: Error } | { type: "CLAIM"; data: AcceptedGatewayTransaction<X>; params: ContractParams; } | { type: "REJECT" } | { type: "SUBMITTED"; data: Partial<SubmittingGatewayTransaction<X>> } | { type: "SUBMIT_ERROR"; data: Partial<SubmittingGatewayTransaction<X>>; error: Error; } | { type: "ACKNOWLEDGE"; data: Partial<SubmittingGatewayTransaction<X>> }; /** Statemachine that tracks individual deposits */ export const buildDepositMachine = <X>() => createMachine< DepositMachineContext<AllGatewayTransactions<X>>, DepositMachineEvent<X>, DepositMachineTypestate<X> >( { id: "RenVMDepositTransaction", initial: DepositStates.CHECKING_COMPLETION, schema: { events: createSchema<DepositMachineEvent<X>>(), context: createSchema< DepositMachineContext<AllGatewayTransactions<X>> >(), }, states: { // Checking if deposit is completed so that we can skip initialization checkingCompletion: { entry: [send("CHECK")], // If we already have completed, no need to listen on: { CHECK: [ { target: "completed", cond: "isCompleted", }, { target: "restoringDeposit" }, ], }, meta: { test: (_: void, state: any) => { assert( !state.context.deposit.error ? true : false, "Error must not exist", ); }, }, }, errorRestoring: { entry: [log((ctx, _) => ctx.deposit.error, "ERROR")], meta: { test: (_: void, state: any) => { assert( state.context.deposit.error ? true : false, "Error must exist", ); }, }, }, restoringDeposit: { entry: sendParent((c, _) => ({ type: "RESTORE", data: c.deposit, })), on: { RESTORED: { target: "restoredDeposit", actions: [assign((_, e) => ({ deposit: e.data }))], }, ERROR: { target: "errorRestoring", actions: assign((c, e) => ({ deposit: { ...c.deposit, error: e.error }, })), }, }, meta: { test: (_: void, state: any) => { assert( !state.context.deposit.error ? true : false, "Error must not exist", ); }, }, }, // Checking deposit internal state to transition to correct machine state restoredDeposit: { // Parent must send restored entry: [send("RESTORED")], on: { RESTORED: [ { target: "srcSettling", cond: "isSrcSettling", }, { target: "srcConfirmed", cond: "isSrcSettled", }, { target: "accepted", cond: "isAccepted", }, // We need to call "submit" again in case // a transaction has been sped up / ran out of gas // so we revert back to accepted when restored instead // of waiting on destination initiation // { // target: "destInitiated", // cond: "isDestInitiated", // }, ].reverse(), }, meta: { test: async () => {} }, }, srcSettling: { entry: sendParent((ctx, _) => ({ type: "SETTLE", hash: ctx.deposit.sourceTxHash, })), on: { CONFIRMED: [ { target: "srcConfirmed", actions: [ assign({ deposit: ({ deposit }, evt) => { if ( isConfirming(deposit) && deposit.sourceTxConfTarget ) { return { ...deposit, sourceTxConfs: largest( deposit.sourceTxConfs, evt.data.sourceTxConfs, ), sourceTxConfTarget: largest( deposit.sourceTxConfTarget, evt.data .sourceTxConfTarget, ), }; } return deposit; }, }), sendParent((ctx, _) => { return { type: "DEPOSIT_UPDATE", data: ctx.deposit, }; }), ], }, ], CONFIRMATION: [ { actions: [ sendParent((ctx, evt) => ({ type: "DEPOSIT_UPDATE", data: { ...ctx.deposit, ...evt.data }, })), assign({ deposit: (context, evt) => ({ ...context.deposit, sourceTxConfs: evt.data?.sourceTxConfs || 0, sourceTxConfTarget: evt.data?.sourceTxConfTarget, }), }), ], }, ], ERROR: [ { actions: [ assign({ deposit: (ctx, evt) => ({ ...ctx.deposit, error: evt.error, }), }), log((ctx, _) => ctx.deposit.error, "ERROR"), ], }, ], }, meta: { test: async () => {} }, }, srcConfirmed: { entry: sendParent((ctx, _) => ({ type: "SIGN", hash: ctx.deposit.sourceTxHash, })), on: { SIGN_ERROR: { target: "errorAccepting", actions: assign({ deposit: (ctx, evt) => ({ ...ctx.deposit, error: evt.error, }), }), }, REVERTED: { target: "rejected", actions: assign({ deposit: (ctx, evt) => ({ ...ctx.deposit, error: evt.error, }), }), }, SIGNED: { target: "accepted", actions: assign({ deposit: (ctx, evt) => ({ ...ctx.deposit, ...evt.data, }), }), }, }, meta: { test: async () => {} }, }, errorAccepting: { entry: [log((ctx, _) => ctx.deposit.error, "ERROR")], meta: { test: (_: void, state: any) => { assert( state.context.deposit.error ? true : false, "error must exist", ); }, }, }, accepted: { entry: sendParent((ctx, _) => { return { type: "CLAIMABLE", data: ctx.deposit, }; }), on: { CLAIM: { target: "claiming", actions: assign({ deposit: (ctx, evt) => ({ ...ctx.deposit, contractParams: evt.params, }), }), }, REJECT: "rejected", }, meta: { test: async () => {} }, }, errorSubmitting: { entry: [ log((ctx, _) => ctx.deposit.error, "ERROR"), sendParent((ctx, _) => { return { type: "CLAIMABLE", data: ctx.deposit, }; }), ], on: { CLAIM: { target: "claiming", actions: assign({ deposit: (ctx, evt) => ({ ...ctx.deposit, contractParams: evt.data, }), }), }, REJECT: "rejected", }, meta: { test: (_: void, state: any) => { assert( state.context.deposit.error ? true : false, "error must exist", ); }, }, }, claiming: { entry: sendParent((ctx) => ({ type: "MINT", hash: ctx.deposit.sourceTxHash, data: isSubmitted(ctx.deposit) && ctx.deposit.contractParams, })), on: { SUBMIT_ERROR: [ { target: "errorSubmitting", actions: [ assign({ deposit: (ctx, evt) => ({ ...ctx.deposit, error: evt.error, }), }), sendParent((ctx, _) => ({ type: "DEPOSIT_UPDATE", data: ctx.deposit, })), ], }, ], SUBMITTED: [ { target: "destInitiated", actions: [ assign({ deposit: (ctx, evt) => ({ ...ctx.deposit, ...evt.data, }), }), sendParent((ctx, _) => ({ type: "DEPOSIT_UPDATE", data: ctx.deposit, })), ], }, ], }, meta: { test: async () => {} }, }, destInitiated: { on: { SUBMIT_ERROR: [ { target: "errorSubmitting", actions: [ assign({ deposit: (ctx, evt) => ({ ...ctx.deposit, error: evt.error, }), }), sendParent((ctx, _) => ({ type: "DEPOSIT_UPDATE", data: ctx.deposit, })), ], }, ], ACKNOWLEDGE: { target: "completed", actions: [ assign({ deposit: (ctx, _) => ({ ...ctx.deposit, completedAt: new Date().getTime(), }), }), ], }, }, meta: { test: async () => {} }, }, rejected: { entry: [ sendParent((ctx, _) => { return { type: "DEPOSIT_UPDATE", data: ctx.deposit, }; }), ], meta: { test: async () => {} }, }, completed: { entry: [ sendParent((ctx, _) => ({ type: "DEPOSIT_COMPLETED", data: ctx.deposit, })), sendParent((ctx, _) => ({ type: "DEPOSIT_UPDATE", data: ctx.deposit, })), ], meta: { test: (_: void, state: any) => { assert( state.context.deposit.completedAt ? true : false, "Must have completedAt timestamp", ); }, }, }, }, }, { guards: { isSrcSettling: ({ deposit }) => isConfirming(deposit) && (deposit.sourceTxConfs || 0) < (deposit.sourceTxConfTarget || Number.POSITIVE_INFINITY), // If we don't know the target, keep settling isSrcSettled: ({ deposit }) => isConfirming(deposit) && (deposit.sourceTxConfs || 0) >= deposit.sourceTxConfTarget, // If we don't know the target, keep settling isAccepted: ({ deposit }) => isAccepted(deposit) && deposit.renSignature ? true : false, isDestInitiated: ({ deposit }) => isMinted(deposit) && deposit.destTxHash ? true : false, isCompleted: ({ deposit }) => isCompleted(deposit) && deposit.completedAt ? true : false, }, }, );
the_stack
import { FC } from "react"; /** * Types related to a page definition * * This is the least strict typing for a page definition. * @see DefaultPageTypes for stricted possible types * @see DefinePageType for defining your own types */ export interface PageTypes { params: Record<string, string>; parentContext: Record<string, any>; data: any; } /** * Strictest definitions for page types */ export type DefaultPageTypes = DefinePageTypes<{ params: never; parentContext: RootContext; data: undefined; }>; /** * Utility type for defining a page with strict types * * Use the type parameter to define strict types for data, params, * context etc. */ export type DefinePageTypes<T extends Partial<PageTypes>> = { params: T extends { params: any } ? T["params"] : never; parentContext: T extends { parentContext: any } ? T["parentContext"] : RootContext; data: T extends { data: any } ? T["data"] : undefined; }; /** * Utility type for defining a page with strict types for data and params while * inferring the type for context from the type definitions of the * parent layout */ export type DefinePageTypesUnder< P extends LayoutTypes, T extends Partial<PageTypes & { parentContext: never }> = {}, > = { params: T extends { params: any } ? T["params"] : never; parentContext: LayoutContext<P>; data: T extends { data: any } ? T["data"] : undefined; }; /** * Types related to a layout definition * * This is the least strict typing for a laout definition. * @see DefaultLayoutTypes for stricted possible types * @see DefineLayoutType for defining your own types */ export interface LayoutTypes extends PageTypes { contextOverrides: Record<string, any>; } /** * Utility type for defining a page with strict types * * Use the type parameter to define strict types for data, params, * context etc. */ export type DefaultLayoutTypes = DefineLayoutTypes<{ params: never; parentContext: RootContext; data: undefined; }>; /** * Utility type for defining a layout with strict types * * Use the type parameter to define strict types for data, params, * context etc. */ export type DefineLayoutTypes<T extends Partial<LayoutTypes>> = { params: T extends { params: any } ? T["params"] : never; parentContext: T extends { parentContext: any } ? T["parentContext"] : RootContext; data: T extends { data: any } ? T["data"] : undefined; contextOverrides: T extends { contextOverrides: any } ? T["contextOverrides"] : Record<string, never>; }; /** * Utility type for defining a page with strict types for data and params while * inferring the type for context from the type definitions of the * parent layout */ export type DefineLayoutTypesUnder< P extends LayoutTypes, T extends Partial<LayoutTypes & { parentContext: never }> = {}, > = { params: T extends { params: any } ? T["params"] : never; parentContext: LayoutContext<P>; data: T extends { data: any } ? T["data"] : undefined; contextOverrides: T extends { contextOverrides: any } ? T["contextOverrides"] : Record<string, never>; }; export interface GetCacheKeyArgs<T extends PageTypes = DefaultPageTypes> { /** Current URL */ url: URL; /** Matching path, i.e. "/aaa/[param]" */ match?: string; /** Current path parameters */ params: T["params"]; /** Context passed down from parent layout load functions */ context: T["parentContext"]; } export type GetCacheKeyFunc<T extends PageTypes = DefaultPageTypes> = ( args: GetCacheKeyArgs<T>, ) => any; export interface LoadArgs<T extends PageTypes = DefaultPageTypes> extends GetCacheKeyArgs<T> { /** Fetch function to make requests that includes credentials on both the client and the server */ fetch: typeof fetch; /** Locale */ locale: string; /** Data loading helpers */ helpers: LoadHelpers; } export interface LoadHelpers {} export type PageLoadFunc<T extends PageTypes = DefaultPageTypes> = ( args: LoadArgs<T>, ) => PageLoadResult<T["data"]> | Promise<PageLoadResult<T["data"]>>; export type LayoutLoadFunc<T extends LayoutTypes = DefaultLayoutTypes> = ( args: LoadArgs<T>, ) => | LayoutLoadResult<T["data"], T["contextOverrides"]> | Promise<LayoutLoadResult<T["data"], T["contextOverrides"]>>; /** * Props passed to a page component */ export interface PageProps<T extends PageTypes = DefaultPageTypes> extends GetCacheKeyArgs<T> { /** Data returned from the load function */ data: T["data"]; /** Reload function to invalidate current data and reload the page */ reload(): void; /** Custom hook to invalidate current data and reload the page under certain circumstances */ useReload(params: ReloadHookParams): void; } export interface ErrorPageProps<T extends PageTypes = DefaultPageTypes> extends Omit<PageProps<T>, "data"> { /** Error returned from the load function */ error?: ErrorDescription; /** Data returned from the load function */ data?: T["data"]; } /** Utility type to extract the outgoing context type */ export type LayoutContext<T extends LayoutTypes> = Merge< T["parentContext"], T["contextOverrides"] >; /** * Props passed to a layout component */ export interface SimpleLayoutProps<T extends LayoutTypes = DefaultLayoutTypes> extends Omit<GetCacheKeyArgs<T>, "context"> { /** Context as returned from the load function */ context: LayoutContext<T>; /** Data returned from the load function */ data: T["data"]; /** Reload function to invalidate current data and reload the page */ reload(): void; /** Custom hook to invalidate current data and reload the page under certain circumstances */ useReload(params: ReloadHookParams): void; } export interface LayoutProps<T extends LayoutTypes = DefaultLayoutTypes> extends Omit<SimpleLayoutProps<T>, "data"> { /** Error returned from the load function */ error?: ErrorDescription; /** Data returned from the load function. May be unefined if an error has occured. */ data?: T["data"]; } export type Page<T extends PageTypes = DefaultPageTypes> = FC<PageProps<T>>; export type ErrorPage<T extends PageTypes = DefaultPageTypes> = FC< ErrorPageProps<T> >; export type SimpleLayout<T extends LayoutTypes = DefaultLayoutTypes> = FC< SimpleLayoutProps<T> >; export type Layout<T extends LayoutTypes = DefaultLayoutTypes> = FC< LayoutProps<T> >; type Merge<A, B> = Flatten< B extends Record<string, never> ? A : { [key in keyof A]: key extends keyof B ? any : A[key]; } & B >; type Flatten<T> = { [key in keyof T]: T[key] }; export interface PageComponentModule { default: Page | ErrorPage; load?: PageLoadFunc; getCacheKey?: GetCacheKeyFunc; pageOptions?: PageOptions; } export interface PageDefinition { Component: Page | ErrorPage; load?: PageLoadFunc; getCacheKey?: GetCacheKeyFunc; options?: PageOptions; } export interface PageDefinitionModule { default: PageDefinition; } export interface LayoutComponentModule { default?: Layout | SimpleLayout; load?: LayoutLoadFunc; getCacheKey?: GetCacheKeyFunc; layoutOptions?: LayoutOptions; } export interface LayoutDefinition { Component: Layout | SimpleLayout; load?: LayoutLoadFunc; getCacheKey?: GetCacheKeyFunc; options?: LayoutOptions; } export interface PageOptions { /** Can this page or layout handle errors? */ canHandleErrors?: boolean; /** Should this page rendered on the server? */ ssr?: boolean; } export type LayoutOptions = PageOptions; export interface LayoutDefinitionModule { default: LayoutDefinition; } export type PageModule = PageComponentModule | PageDefinitionModule; export type LayoutModule = LayoutComponentModule | LayoutDefinitionModule; export type PageImporter = () => Promise<PageModule> | PageModule; export type LayoutImporter = () => Promise<LayoutModule> | LayoutModule; export interface ReloadHookParams { /** * Reload when window receives focus * @default false * */ focus?: boolean; /** * Reload when the internet connection is restored after a disconnection * @default false * */ reconnect?: boolean; /** * Set to i.e. 15_000 to reload every 15 seconds * @default false * */ interval?: number | false; /** * Set to true to reload on interval even when the window has no focus * @default false * */ background?: boolean; } /** Description of an error */ export interface ErrorDescription { message: string; status?: number; stack?: string; detail?: any; } export type PageLoadResult<T = unknown> = | PageLoadSuccessResult<T> | LoadRedirectResult | LoadErrorResult; export type LayoutLoadResult< T = unknown, C extends Record<string, any> = Record<string, any>, > = LayoutLoadSuccessResult<T, C> | LoadRedirectResult | LoadErrorResult; export interface PageLoadSuccessResult<T = unknown> { /** HTTP status, should be 2xx or 3xx for redirect */ status?: number; /** Data to be passed to the page component */ data: T; /** Value to be returned in the Cache-Control header */ cacheControl?: string; /** Should this page be prerendered? */ prerender?: boolean; /** Should this page be crawled to discover more pages to pre-render? */ crawl?: boolean; } export interface LayoutLoadSuccessResult< T = unknown, C extends Record<string, unknown> = Record<string, unknown>, > { /** Status (can be changed in inner layouts/components) */ status?: number; /** Data to be passed to the layout component */ data: T; /** Value to be returned in the Cache-Control header */ cacheControl?: string; /** Context to be passed down to nested layouts and pages */ context?: C; /** Should this page be prerendered? */ prerender?: boolean; /** Should this page be crawled to discover more pages to pre-render? */ crawl?: boolean; } export interface LoadRedirectResult { /** HTTP status, should be 3xx */ status?: number; /** Redirect location */ redirect: string | URL; /** Value to be returned in the Cache-Control header */ cacheControl?: string; /** Should this page be prerendered? */ prerender?: boolean; /** Should this page be crawled to discover more pages to pre-render? */ crawl?: boolean; } export interface LoadErrorResult { // HTTP status, should be 4xx or 5xx status?: number; // An error object describing the error error: ErrorDescription; /** Value to be returned in the Cache-Control header */ cacheControl?: string; /** Should this page be prerendered? */ prerender?: boolean; /** Should this page be crawled to discover more pages to pre-render? */ crawl?: boolean; } // Return value of useRouter custom hook export interface RouterInfo { currentUrl: URL; params: Record<string, string>; pendingUrl?: URL; } interface RawRequestBase { ip: string; url: URL; method: string; headers: Headers; originalIp: string; originalUrl: URL; } interface RakkasRequestBase<C = Record<string, unknown>> extends RawRequestBase { params: Record<string, string>; context: C; } interface EmptyBody { type: "empty"; body?: undefined; } interface BinaryBody { type: "binary"; body: Uint8Array; } interface TextBody { type: "text"; body: string; } interface FormDataBody { type: "form-data"; body: URLSearchParams; } interface JsonBody { type: "json"; body: any; } export type RakkasRequestBodyAndType = | EmptyBody | TextBody | BinaryBody | FormDataBody | JsonBody; export type RawRequest = RawRequestBase & RakkasRequestBodyAndType; export type RakkasRequest<C = Record<string, unknown>> = RakkasRequestBase<C> & RakkasRequestBodyAndType; export interface RakkasResponse { status?: number; headers?: | Record<string, string | string[] | undefined> | Array<[string, string | string[] | undefined]>; body?: unknown; prerender?: boolean; } export type RequestHandler = ( request: RakkasRequest, ) => RakkasResponse | Promise<RakkasResponse>; export type RakkasMiddleware = ( request: RakkasRequest, next: (request: RakkasRequest) => Promise<RakkasResponse>, ) => RakkasResponse | Promise<RakkasResponse>; export interface RootContext {} export type ServePageHook = ( request: RawRequest, renderPage: ( request: RawRequest, context?: RootContext, options?: PageRenderOptions, ) => Promise<RakkasResponse>, locale?: string, ) => RakkasResponse | Promise<RakkasResponse>; export interface PageRenderOptions { /** Wrap the rendered page in server-side providers */ wrap?(page: JSX.Element): JSX.Element; /** Get extra HTML to be emitted to the head */ getHeadHtml?(): string; /** Create the helpers object to be passed to load functions */ createLoadHelpers?( fetch: typeof globalThis.fetch, ): LoadHelpers | Promise<LoadHelpers>; /** Custom rendering */ renderToString?(app: JSX.Element): string | Promise<string>; } export interface ClientHooks { /** Do initialization work before hydration. If you return a promise, Rakkas will delay hydration until it resolves */ beforeStartClient?(rootContext: RootContext): void | Promise<void>; /** You can wrap the client-side app in a provider here. Useful for integrating with, e.g., Redux, Apollo client etc. */ wrap?(page: JSX.Element, rootContext: RootContext): JSX.Element; /** Initialize your client-side load helpers here */ createLoadHelpers?( rootContext: RootContext, ): LoadHelpers | Promise<LoadHelpers>; } export interface CommonHooks { /** Decode the locale from the URL and optionally rewrite the URL. * If the URL belongs to an international redirection page, return a redirect object * with keys as the locales and values as the redirect URLs. */ extractLocale?( url: URL, ): | { locale: string; url?: URL | string } | { redirect: Record<string, URL | string> }; }
the_stack
module android.view{ import Rect = android.graphics.Rect; /** * Standard constants and tools for placing an object within a potentially * larger container. */ export class Gravity{ /** Constant indicating that no gravity has been set **/ static NO_GRAVITY = 0x0000; /** Raw bit indicating the gravity for an axis has been specified. */ static AXIS_SPECIFIED = 0x0001; /** Raw bit controlling how the left/top edge is placed. */ static AXIS_PULL_BEFORE = 0x0002; /** Raw bit controlling how the right/bottom edge is placed. */ static AXIS_PULL_AFTER = 0x0004; /** Raw bit controlling whether the right/bottom edge is clipped to its * container, based on the gravity direction being applied. */ static AXIS_CLIP = 0x0008; /** Bits defining the horizontal axis. */ static AXIS_X_SHIFT = 0; /** Bits defining the vertical axis. */ static AXIS_Y_SHIFT = 4; /** Push object to the top of its container, not changing its size. */ static TOP = (Gravity.AXIS_PULL_BEFORE|Gravity.AXIS_SPECIFIED)<<Gravity.AXIS_Y_SHIFT; /** Push object to the bottom of its container, not changing its size. */ static BOTTOM = (Gravity.AXIS_PULL_AFTER|Gravity.AXIS_SPECIFIED)<<Gravity.AXIS_Y_SHIFT; /** Push object to the left of its container, not changing its size. */ static LEFT = (Gravity.AXIS_PULL_BEFORE|Gravity.AXIS_SPECIFIED)<<Gravity.AXIS_X_SHIFT; /** Push object to the right of its container, not changing its size. */ static RIGHT = (Gravity.AXIS_PULL_AFTER|Gravity.AXIS_SPECIFIED)<<Gravity.AXIS_X_SHIFT; static START = Gravity.LEFT; static END = Gravity.RIGHT; /** Place object in the vertical center of its container, not changing its * size. */ static CENTER_VERTICAL = Gravity.AXIS_SPECIFIED<<Gravity.AXIS_Y_SHIFT; /** Grow the vertical size of the object if needed so it completely fills * its container. */ static FILL_VERTICAL = Gravity.TOP|Gravity.BOTTOM; /** Place object in the horizontal center of its container, not changing its * size. */ static CENTER_HORIZONTAL = Gravity.AXIS_SPECIFIED<<Gravity.AXIS_X_SHIFT; /** Grow the horizontal size of the object if needed so it completely fills * its container. */ static FILL_HORIZONTAL = Gravity.LEFT|Gravity.RIGHT; /** Place the object in the center of its container in both the vertical * and horizontal axis, not changing its size. */ static CENTER = Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL; /** Grow the horizontal and vertical size of the object if needed so it * completely fills its container. */ static FILL = Gravity.FILL_VERTICAL|Gravity.FILL_HORIZONTAL; /** Flag to clip the edges of the object to its container along the * vertical axis. */ static CLIP_VERTICAL = Gravity.AXIS_CLIP<<Gravity.AXIS_Y_SHIFT; /** Flag to clip the edges of the object to its container along the * horizontal axis. */ static CLIP_HORIZONTAL = Gravity.AXIS_CLIP<<Gravity.AXIS_X_SHIFT; /** Raw bit controlling whether the layout direction is relative or not (Gravity.START/Gravity.END instead of * absolute Gravity.LEFT/Gravity.RIGHT). */ //static RELATIVE_LAYOUT_DIRECTION = 0x00800000; /** * Binary mask to get the absolute horizontal gravity of a gravity. */ static HORIZONTAL_GRAVITY_MASK = (Gravity.AXIS_SPECIFIED | Gravity.AXIS_PULL_BEFORE | Gravity.AXIS_PULL_AFTER) << Gravity.AXIS_X_SHIFT; /** * Binary mask to get the vertical gravity of a gravity. */ static VERTICAL_GRAVITY_MASK = (Gravity.AXIS_SPECIFIED | Gravity.AXIS_PULL_BEFORE | Gravity.AXIS_PULL_AFTER) << Gravity.AXIS_Y_SHIFT; static RELATIVE_HORIZONTAL_GRAVITY_MASK = Gravity.HORIZONTAL_GRAVITY_MASK; /** Special constant to enable clipping to an overall display along the * vertical dimension. This is not applied by default by * {@link #apply(int, int, int, Rect, int, int, Rect)}; you must do so * yourself by calling {@link #applyDisplay}. */ static DISPLAY_CLIP_VERTICAL = 0x10000000; /** Special constant to enable clipping to an overall display along the * horizontal dimension. This is not applied by default by * {@link #apply(int, int, int, Rect, int, int, Rect)}; you must do so * yourself by calling {@link #applyDisplay}. */ static DISPLAY_CLIP_HORIZONTAL = 0x01000000; /** Push object to x-axis position at the start of its container, not changing its size. */ //static START = Gravity.RELATIVE_LAYOUT_DIRECTION | Gravity.LEFT; /** Push object to x-axis position at the end of its container, not changing its size. */ //static END = Gravity.RELATIVE_LAYOUT_DIRECTION | Gravity.RIGHT; /** * Binary mask for the horizontal gravity and script specific direction bit. */ //static RELATIVE_HORIZONTAL_GRAVITY_MASK = Gravity.START | Gravity.END; /** * Apply a gravity constant to an object and take care if layout direction is RTL or not. * * @param gravity The desired placement of the object, as defined by the * constants in this class. * @param w The horizontal size of the object. * @param h The vertical size of the object. * @param container The frame of the containing space, in which the object * will be placed. Should be large enough to contain the * width and height of the object. * @param outRect Receives the computed frame of the object in its * container. * @param layoutDirection The layout direction. * * @see View#LAYOUT_DIRECTION_LTR * @see View#LAYOUT_DIRECTION_RTL */ static apply(gravity:number, w:number, h:number, container:Rect, outRect:Rect, layoutDirection?:number) { let xAdj = 0, yAdj = 0; if(layoutDirection!=null) gravity = Gravity.getAbsoluteGravity(gravity, layoutDirection); switch (gravity & ((Gravity.AXIS_PULL_BEFORE | Gravity.AXIS_PULL_AFTER) << Gravity.AXIS_X_SHIFT)) { case 0: outRect.left = container.left + ((container.right - container.left - w) / 2) + xAdj; outRect.right = outRect.left + w; if ((gravity & (Gravity.AXIS_CLIP << Gravity.AXIS_X_SHIFT)) == (Gravity.AXIS_CLIP << Gravity.AXIS_X_SHIFT)) { if (outRect.left < container.left) { outRect.left = container.left; } if (outRect.right > container.right) { outRect.right = container.right; } } break; case Gravity.AXIS_PULL_BEFORE << Gravity.AXIS_X_SHIFT: outRect.left = container.left + xAdj; outRect.right = outRect.left + w; if ((gravity & (Gravity.AXIS_CLIP << Gravity.AXIS_X_SHIFT)) == (Gravity.AXIS_CLIP << Gravity.AXIS_X_SHIFT)) { if (outRect.right > container.right) { outRect.right = container.right; } } break; case Gravity.AXIS_PULL_AFTER << Gravity.AXIS_X_SHIFT: outRect.right = container.right - xAdj; outRect.left = outRect.right - w; if ((gravity & (Gravity.AXIS_CLIP << Gravity.AXIS_X_SHIFT)) == (Gravity.AXIS_CLIP << Gravity.AXIS_X_SHIFT)) { if (outRect.left < container.left) { outRect.left = container.left; } } break; default: outRect.left = container.left + xAdj; outRect.right = container.right + xAdj; break; } switch (gravity & ((Gravity.AXIS_PULL_BEFORE | Gravity.AXIS_PULL_AFTER) << Gravity.AXIS_Y_SHIFT)) { case 0: outRect.top = container.top + ((container.bottom - container.top - h) / 2) + yAdj; outRect.bottom = outRect.top + h; if ((gravity & (Gravity.AXIS_CLIP << Gravity.AXIS_Y_SHIFT)) == (Gravity.AXIS_CLIP << Gravity.AXIS_Y_SHIFT)) { if (outRect.top < container.top) { outRect.top = container.top; } if (outRect.bottom > container.bottom) { outRect.bottom = container.bottom; } } break; case Gravity.AXIS_PULL_BEFORE << Gravity.AXIS_Y_SHIFT: outRect.top = container.top + yAdj; outRect.bottom = outRect.top + h; if ((gravity & (Gravity.AXIS_CLIP << Gravity.AXIS_Y_SHIFT)) == (Gravity.AXIS_CLIP << Gravity.AXIS_Y_SHIFT)) { if (outRect.bottom > container.bottom) { outRect.bottom = container.bottom; } } break; case Gravity.AXIS_PULL_AFTER << Gravity.AXIS_Y_SHIFT: outRect.bottom = container.bottom - yAdj; outRect.top = outRect.bottom - h; if ((gravity & (Gravity.AXIS_CLIP << Gravity.AXIS_Y_SHIFT)) == (Gravity.AXIS_CLIP << Gravity.AXIS_Y_SHIFT)) { if (outRect.top < container.top) { outRect.top = container.top; } } break; default: outRect.top = container.top + yAdj; outRect.bottom = container.bottom + yAdj; break; } } /** * <p>Convert script specific gravity to absolute horizontal value.</p> * * if horizontal direction is LTR, then START will set LEFT and END will set RIGHT. * if horizontal direction is RTL, then START will set RIGHT and END will set LEFT. * * * @param gravity The gravity to convert to absolute (horizontal) values. * @param layoutDirection The layout direction. * @return gravity converted to absolute (horizontal) values. */ static getAbsoluteGravity(gravity:number, layoutDirection?:number):number { return gravity;//no need parse. } static parseGravity(gravityStr:string, defaultGravity=Gravity.NO_GRAVITY):number { if(!gravityStr) return defaultGravity; let gravity = null; try { let parts = gravityStr.split("|"); for(let part of parts){ let g = Gravity[part.toUpperCase()]; if (Number.isInteger(g)) gravity |= g; } } catch (e) { console.error(e); } if(Number.isNaN(gravity)) return defaultGravity; return gravity; } } }
the_stack
import { ICustomMediaKeys, ICustomMediaKeySession, ICustomMediaKeySystemAccess, } from "../../compat"; import { ICustomError } from "../../errors"; import { ISharedReference } from "../../utils/reference"; import LoadedSessionsStore from "./utils/loaded_sessions_store"; import PersistentSessionsStore from "./utils/persistent_sessions_store"; /** Information about the encryption initialization data. */ export interface IInitializationDataInfo { /** * The initialization data type - or the format of the `data` attribute (e.g. * "cenc"). * `undefined` if unknown. */ type : string | undefined; /** * The key ids linked to those initialization data. * This should be the key ids for the key concerned by the media which have * the present initialization data. * * `undefined` when not known (different from an empty array - which would * just mean that there's no key id involved). */ keyIds? : Uint8Array[]; /** Every initialization data for that type. */ values: Array<{ /** * Hex encoded system id, which identifies the key system. * https://dashif.org/identifiers/content_protection/ * * If `undefined`, we don't know the system id for that initialization data. * In that case, the initialization data might even be a concatenation of * the initialization data from multiple system ids. */ systemId: string | undefined; /** * The initialization data itself for that type and systemId. * For example, with "cenc" initialization data found in an ISOBMFF file, * this will be the whole PSSH box. */ data: Uint8Array; }>; } /** Event emitted when a minor - recoverable - error happened. */ export interface IEMEWarningEvent { type : "warning"; value : ICustomError; } /** * Event emitted when we receive an "encrypted" event from the browser. * This is usually sent when pushing an initialization segment, if it stores * encryption information. */ export interface IEncryptedEvent { type: "encrypted-event-received"; value: IInitializationDataInfo; } /** * Sent when a MediaKeys has been created (or is already created) for the * current content. * This is necessary before creating a MediaKeySession which will allow * encryption keys to be communicated. * * It carries a shared reference (`canAttachMediaKeys`) that should be setted to * `true` to indicate that RxPlayer's EME logic can start to attach the * `MediaKeys` instance to the HTMLMediaElement. */ export interface ICreatedMediaKeysEvent { type: "created-media-keys"; value: { /** The MediaKeySystemAccess which allowed to create the MediaKeys instance. */ mediaKeySystemAccess: MediaKeySystemAccess | ICustomMediaKeySystemAccess; /** * Hex-encoded identifier for the key system used. * A list of available IDs can be found here: * https://dashif.org/identifiers/content_protection/ * * This ID can be used to select the encryption initialization data to send * to the EMEManager. * * Note that this is only for optimization purposes (e.g. to not * unnecessarily wait for new encryption initialization data to arrive when * those linked to the right key system is already available) as sending all * available encryption initialization data should also work in all cases. * * Can be `undefined` in two cases: * * - the current system ID is not known * * - the current system ID is known, but we don't want to communicate it * to ensure all encryption initialization data is still sent. * This is usually done to work-around retro-compatibility issues with * older persisted decryption session. */ initializationDataSystemId : string | undefined; /** The MediaKeys instance. */ mediaKeys : MediaKeys | ICustomMediaKeys; /** Stores allowing to cache MediaKeySession instances. */ stores : IMediaKeySessionStores; /** key system options considered. */ options : IKeySystemOption; /** * Shared reference that should be set to `true` once the `MediaKeys` * instance can be attached to the HTMLMediaElement. */ canAttachMediaKeys: ISharedReference<boolean>; }; } /** * Sent when the created (or already created) MediaKeys is attached to the * current HTMLMediaElement element. * On some peculiar devices, we have to wait for that step before the first * media segments are to be pushed to avoid issues. * Because this event is sent after a MediaKeys is created, you will always have * a "created-media-keys" event before an "attached-media-keys" event. */ export interface IAttachedMediaKeysEvent { type: "attached-media-keys"; value: { /** The MediaKeySystemAccess which allowed to create the MediaKeys instance. */ mediaKeySystemAccess: MediaKeySystemAccess | ICustomMediaKeySystemAccess; /** The MediaKeys instance. */ mediaKeys : MediaKeys | ICustomMediaKeys; stores : IMediaKeySessionStores; options : IKeySystemOption; }; } /** * Emitted when the initialization data received through an encrypted event or * through the EMEManager argument can already be decipherable without going * through the usual license-fetching logic. * This is usually because the MediaKeySession for this encryption key has * already been created. */ export interface IInitDataIgnoredEvent { type: "init-data-ignored"; value : { initializationData : IInitializationDataInfo }; } /** * Emitted when a "message" event is sent. * Those events generally allows the CDM to ask for data such as the license or * a server certificate. * As such, we will call the corresponding `getLicense` callback immediately * after this event is sent. * * Depending on the return of the getLicense call, we will then either emit a * "warning" event and retry the call (for when it failed but will be retried), * throw (when it failed with no retry left and no fallback policy is set), emit * a "blacklist-protection-data-event" (for when it failed with no retry left * but a fallback policy is set), emit a "session-updated" event (for when the * call resolved with some data) or emit a "no-update" event (for when the call * resolved with `null`). */ export interface ISessionMessageEvent { type: "session-message"; value : { messageType : string; initializationData : IInitializationDataInfo; }; } /** * Emitted when a `getLicense` call resolves with null. * In that case, we do not call `MediaKeySession.prototype.update` and no * `session-updated` event will be sent. */ export interface INoUpdateEvent { type : "no-update"; value : { initializationData: IInitializationDataInfo }; } /** * Some key ids have updated their status. * * We put them in two different list: * * - `blacklistedKeyIDs`: Those key ids won't be used for decryption and the * corresponding media it decrypts should not be pushed to the buffer * Note that a blacklisted key id can become whitelisted in the future. * * - `whitelistedKeyIds`: Those key ids were found and their corresponding * keys are now being considered for decryption. * Note that a whitelisted key id can become blacklisted in the future. * * Note that each `IKeysUpdateEvent` is independent of any other. * * A new `IKeysUpdateEvent` does not completely replace a previously emitted * one, as it can for example be linked to a whole other decryption session. * * However, if a key id is encountered in both an older and a newer * `IKeysUpdateEvent`, only the older status should be considered. */ export interface IKeysUpdateEvent { type: "keys-update"; value: IKeyUpdateValue; } /** Information on key ids linked to a MediaKeySession. */ export interface IKeyUpdateValue { /** * The list of key ids that are blacklisted. * As such, their corresponding keys won't be used by that session, despite * the fact that they were part of the pushed license. * * Reasons for blacklisting a keys depend on options, but mainly involve unmet * output restrictions and CDM internal errors linked to that key id. */ blacklistedKeyIDs : Uint8Array[]; /* * The list of key id linked to that session which are not blacklisted. * Together with `blacklistedKeyIDs` it regroups all key ids linked to the * session. */ whitelistedKeyIds : Uint8Array[]; } /** * Emitted after the `MediaKeySession.prototype.update` function resolves. * This function is called when the `getLicense` callback resolves with a data * different than `null`. */ export interface ISessionUpdatedEvent { type: "session-updated"; value: { session: MediaKeySession | ICustomMediaKeySession; license: ILicense | null; initializationData : IInitializationDataInfo; }; } /** * Event Emitted when specific "protection data" cannot be deciphered and is thus * blacklisted. * * The linked value is the initialization data linked to the content that cannot * be deciphered. */ export interface IBlacklistProtectionDataEvent { type: "blacklist-protection-data"; value: IInitializationDataInfo; } // Every event sent by the EMEManager export type IEMEManagerEvent = IEMEWarningEvent | // minor error IEncryptedEvent | // browser's "encrypted" event ICreatedMediaKeysEvent | IAttachedMediaKeysEvent | IInitDataIgnoredEvent | // initData already handled ISessionMessageEvent | // MediaKeySession event INoUpdateEvent | // `getLicense` returned `null` IKeysUpdateEvent | // Status of keys changed ISessionUpdatedEvent | // `update` call resolved IBlacklistProtectionDataEvent; // initData undecipherable export type ILicense = BufferSource | ArrayBuffer; /** Segment protection sent by the RxPlayer to the EMEManager. */ export interface IContentProtection { /** * Initialization data type. * String describing the format of the initialization data sent through this * event. * https://www.w3.org/TR/eme-initdata-registry/ */ type: string; /** * The key ids linked to those initialization data. * This should be the key ids for the key concerned by the media which have * the present initialization data. * * `undefined` when not known (different from an empty array - which would * just mean that there's no key id involved). */ keyIds? : Uint8Array[]; /** Every initialization data for that type. */ values: Array<{ /** * Hex encoded system id, which identifies the key system. * https://dashif.org/identifiers/content_protection/ */ systemId: string; /** * The initialization data itself for that type and systemId. * For example, with "cenc" initialization data found in an ISOBMFF file, * this will be the whole PSSH box. */ data: Uint8Array; }>; } // Emitted after the `onKeyStatusesChange` callback has been called export interface IKeyStatusChangeHandledEvent { type: "key-status-change-handled"; value: { session: MediaKeySession | ICustomMediaKeySession; license: ILicense|null; }; } // Emitted after the `getLicense` callback has been called export interface IKeyMessageHandledEvent { type: "key-message-handled"; value: { session: MediaKeySession | ICustomMediaKeySession; license: ILicense|null; }; } // Infos indentifying a MediaKeySystemAccess export interface IKeySystemAccessInfos { keySystemAccess: MediaKeySystemAccess | ICustomMediaKeySystemAccess; keySystemOptions: IKeySystemOption; } /** Stores helping to create and retrieve MediaKeySessions. */ export interface IMediaKeySessionStores { /** Retrieve MediaKeySessions already loaded on the current MediaKeys instance. */ loadedSessionsStore : LoadedSessionsStore; /** Retrieve persistent MediaKeySessions already created. */ persistentSessionsStore : PersistentSessionsStore | null; } /** * Data stored in a persistent MediaKeySession storage. * Has to be versioned to be able to play MediaKeySessions persisted in an old * RxPlayer version when in a new one. */ export type IPersistentSessionInfo = IPersistentSessionInfoV3 | IPersistentSessionInfoV2 | IPersistentSessionInfoV1 | IPersistentSessionInfoV0; /** Wrap initialization data and allow linearization of it into base64. */ interface IInitDataContainer { /** The initData itself. */ initData : Uint8Array; /** * Convert it to base64. * `toJSON` is specially interpreted by JavaScript engines to be able to rely * on it when calling `JSON.stringify` on it or any of its parent objects: * https://tc39.es/ecma262/#sec-serializejsonproperty */ toJSON() : string; } /** * Stored information about a single persistent `MediaKeySession`, when created * since the v3.24.0 RxPlayer version included. */ export interface IPersistentSessionInfoV3 { /** Version for this object. */ version : 3; /** The persisted MediaKeySession's `id`. Used to load it at a later time. */ sessionId : string; /** Type giving information about the format of the initialization data. */ initDataType : string | undefined; /** * Every saved initialization data for that session, used as IDs. * Elements are sorted in systemId alphabetical order (putting the `undefined` * ones last). */ values: Array<{ /** * Hex encoded system id, which identifies the key system. * https://dashif.org/identifiers/content_protection/ * * If `undefined`, we don't know the system id for that initialization data. * In that case, the initialization data might even be a concatenation of * the initialization data from multiple system ids. */ systemId : string | undefined; /** * A hash of the initialization data (generated by the `hashBuffer` function, * at the time of v3.20.1 at least). Allows for a faster comparison than just * comparing initialization data multiple times. */ hash : number; /** * The initialization data associated to the systemId, wrapped in a * container to allow efficient serialization. */ data : IInitDataContainer; }>; } /** * Stored information about a single persistent `MediaKeySession`, when created * between the RxPlayer versions v3.21.0 and v3.21.1 included. * The previous implementation (version 1) was fine enough but did not linearize * well due to it containing an Uint8Array. This data is now wrapped into a * container which will convert it to base64 when linearized through * `JSON.stringify`. */ export interface IPersistentSessionInfoV2 { /** Version for this object. */ version : 2; /** The persisted MediaKeySession's `id`. Used to load it at a later time. */ sessionId : string; /** * The initialization data associated to the `MediaKeySession`, wrapped in a * container to allow efficient linearization. */ initData : IInitDataContainer; /** * A hash of the initialization data (generated by the `hashBuffer` function, * at the time of v3.20.1 at least). Allows for a faster comparison than just * comparing initialization data multiple times. */ initDataHash : number; /** Type giving information about the format of the initialization data. */ initDataType? : string | undefined; } /** * Stored information about a single persistent `MediaKeySession`, when created * in the v3.20.1 RxPlayer version. * Add sub-par (as in not performant) collision prevention by setting both * the hash of the initialization data and the initialization data itself. * The hash could be checked first for a fast comparison, then the full data. * Had to do this way because this structure is documented in the API as being * put in an array with one element per sessionId. * We might implement a HashMap in future versions instead. */ export interface IPersistentSessionInfoV1 { /** Version for this object. */ version : 1; /** The persisted MediaKeySession's `id`. Used to load it at a later time. */ sessionId : string; /** The initialization data associated to the `MediaKeySession`, untouched. */ initData : Uint8Array; /** * A hash of the initialization data (generated by the `hashBuffer` function, * at the time of v3.20.1 at least). Allows for a faster comparison than just * comparing initialization data multiple times. */ initDataHash : number; /** Type giving information about the format of the initialization data. */ initDataType? : string | undefined; } /** * Stored information about a single persistent `MediaKeySession`, when created * in RxPlayer versions before the v3.20.1 * Here we have no collision detection. We could theorically load the wrong * persistent session. */ export interface IPersistentSessionInfoV0 { /** Version for this object. Usually not defined here. */ version? : undefined; /** The persisted MediaKeySession's `id`. Used to load it at a later time. */ sessionId : string; /** This initData is a hash of a real one. Here we don't handle collision. */ initData : number; /** Type giving information about the format of the initialization data. */ initDataType? : string | undefined; } /** Persistent MediaKeySession storage interface. */ export interface IPersistentSessionStorage { /** Load persistent MediaKeySessions previously saved through the `save` callback. */ load() : IPersistentSessionInfo[]; /** * Save new persistent MediaKeySession information. * The given argument should be returned by the next `load` call. */ save(x : IPersistentSessionInfo[]) : void; /** * By default, MediaKeySessions persisted through an older version of the * RxPlayer will still be available under this version. * * By setting this value to `true`, we can disable that condition in profit of * multiple optimizations (to load a content faster, use less CPU resources * etc.). * * As such, if being able to load MediaKeySession persisted via older version * is not important to you, we recommend setting that value to `true`. */ disableRetroCompatibility? : boolean; } /** Options related to a single key system. */ export interface IKeySystemOption { /** * Key system wanted. * * Either as a canonical name (like "widevine" or "playready") or as the * complete reverse domain name denomination (e.g. "com.widevine.alpha"). */ type : string; /** Logic used to fetch the license */ getLicense : (message : Uint8Array, messageType : string) => Promise<BufferSource | null> | BufferSource | null; /** Supplementary optional configuration for the getLicense call. */ getLicenseConfig? : { retry? : number; timeout? : number; }; /** * Optional `serverCertificate` we will try to set to speed-up the * license-fetching process. * `null` or `undefined` indicates that no serverCertificate should be * set. */ serverCertificate? : BufferSource | null; /** * If `true`, we will try to persist the licenses obtained as well as try to * load already-persisted licenses. */ persistentLicense? : boolean; /** Storage mechanism used to store and retrieve information on stored licenses. */ licenseStorage? : IPersistentSessionStorage; /** * If true, we will require that the CDM is able to persist state. * See EME specification related to the `persistentState` configuration. */ persistentStateRequired? : boolean; /** * If true, we will require that the CDM should use distinctive identyfiers. * See EME specification related to the `distinctiveIdentifier` configuration. */ distinctiveIdentifierRequired? : boolean; /** * If true, all open MediaKeySession (used to decrypt the content) will be * closed when the current playback stops. */ closeSessionsOnStop? : boolean; singleLicensePer? : "content" | "init-data"; /** * Maximum number of `MediaKeySession` that should be created on the same * MediaKeys. */ maxSessionCacheSize? : number; /** Callback called when one of the key's status change. */ onKeyStatusesChange? : (evt : Event, session : MediaKeySession | ICustomMediaKeySession) => Promise<BufferSource | null> | BufferSource | null; /** Allows to define custom robustnesses value for the video data. */ videoRobustnesses?: Array<string|undefined>; /** Allows to define custom robustnesses value for the audio data. */ audioRobustnesses?: Array<string|undefined>; /** * If explicitely set to `false`, we won't throw on error when a used license * is expired. */ throwOnLicenseExpiration? : boolean; /** * If set to `true`, we will not wait until the MediaKeys instance is attached * to the media element before pushing segments to it. * Setting it to `true` might be needed on some targets to work-around a * deadlock in the browser-side logic (or most likely the CDM implementation) * but it can also break playback of contents with both encrypted and * unencrypted data, most especially on Chromium and Chromium-derived browsers. */ disableMediaKeysAttachmentLock? : boolean; /** * Enable fallback logic, to switch to other Representations when a key linked * to another one fails with an error. * Configure only this if you have contents with multiple keys depending on * the Representation (also known as qualities/profiles). */ fallbackOn? : { /** * If `true`, we will fallback when a key obtain the "internal-error" status. * If `false`, we fill just throw a fatal error instead. */ keyInternalError? : boolean; /** * If `true`, we will fallback when a key obtain the "internal-error" status. * If `false`, we fill just throw a fatal error instead. */ keyOutputRestricted? : boolean; }; }
the_stack
import { ChangeDetectionStrategy } from '../change_detection/constants'; import { Provider } from '../core'; import { NgModuleDef } from '../metadata/ng_module'; import { RendererType2 } from '../render/api'; import { Type } from '../type'; import { ComponentDefFeature, ComponentDefInternal, ComponentQuery, ComponentTemplate, ComponentType, DirectiveDefFeature, DirectiveDefInternal, DirectiveType, DirectiveTypesOrFactory, PipeDefInternal, PipeType, PipeTypesOrFactory } from './interfaces/definition'; import { CssSelectorList, SelectorFlags } from './interfaces/projection'; /** * Create a component definition object. * * * # Example * ``` * class MyDirective { * // Generated by Angular Template Compiler * // [Symbol] syntax will not be supported by TypeScript until v2.7 * static ngComponentDef = defineComponent({ * ... * }); * } * ``` */ export declare function defineComponent<T>(componentDefinition: { /** * Directive type, needed to configure the injector. */ type: Type<T>; /** The selectors that will be used to match nodes to this component. */ selectors: CssSelectorList; /** * Factory method used to create an instance of directive. */ factory: () => T; /** * Static attributes to set on host element. * * Even indices: attribute name * Odd indices: attribute value */ attributes?: string[]; /** * A map of input names. * * The format is in: `{[actualPropertyName: string]:(string|[string, string])}`. * * Given: * ``` * class MyComponent { * @Input() * publicInput1: string; * * @Input('publicInput2') * declaredInput2: string; * } * ``` * * is described as: * ``` * { * publicInput1: 'publicInput1', * declaredInput2: ['declaredInput2', 'publicInput2'], * } * ``` * * Which the minifier may translate to: * ``` * { * minifiedPublicInput1: 'publicInput1', * minifiedDeclaredInput2: [ 'publicInput2', 'declaredInput2'], * } * ``` * * This allows the render to re-construct the minified, public, and declared names * of properties. * * NOTE: * - Because declared and public name are usually same we only generate the array * `['declared', 'public']` format when they differ. * - The reason why this API and `outputs` API is not the same is that `NgOnChanges` has * inconsistent behavior in that it uses declared names rather than minified or public. For * this reason `NgOnChanges` will be deprecated and removed in future version and this * API will be simplified to be consistent with `output`. */ inputs?: { [P in keyof T]?: string | [string, string]; }; /** * A map of output names. * * The format is in: `{[actualPropertyName: string]:string}`. * * Which the minifier may translate to: `{[minifiedPropertyName: string]:string}`. * * This allows the render to re-construct the minified and non-minified names * of properties. */ outputs?: { [P in keyof T]?: string; }; /** * Function executed by the parent template to allow child directive to apply host bindings. */ hostBindings?: (directiveIndex: number, elementIndex: number) => void; /** * Function to create instances of content queries associated with a given directive. */ contentQueries?: (() => void); /** Refreshes content queries associated with directives in a given view */ contentQueriesRefresh?: ((directiveIndex: number, queryIndex: number) => void); /** * Defines the name that can be used in the template to assign this directive to a variable. * * See: {@link Directive.exportAs} */ exportAs?: string; /** * Template function use for rendering DOM. * * This function has following structure. * * ``` * function Template<T>(ctx:T, creationMode: boolean) { * if (creationMode) { * // Contains creation mode instructions. * } * // Contains binding update instructions * } * ``` * * Common instructions are: * Creation mode instructions: * - `elementStart`, `elementEnd` * - `text` * - `container` * - `listener` * * Binding update instructions: * - `bind` * - `elementAttribute` * - `elementProperty` * - `elementClass` * - `elementStyle` * */ template: ComponentTemplate<T>; /** * Additional set of instructions specific to view query processing. This could be seen as a * set of instruction to be inserted into the template function. * * Query-related instructions need to be pulled out to a specific function as a timing of * execution is different as compared to all other instructions (after change detection hooks but * before view hooks). */ viewQuery?: ComponentQuery<T> | null; /** * A list of optional features to apply. * * See: {@link NgOnChangesFeature}, {@link PublicFeature} */ features?: ComponentDefFeature[]; rendererType?: RendererType2; changeDetection?: ChangeDetectionStrategy; /** * Defines the set of injectable objects that are visible to a Directive and its light DOM * children. */ providers?: Provider[]; /** * Defines the set of injectable objects that are visible to its view DOM children. */ viewProviders?: Provider[]; /** * Registry of directives and components that may be found in this component's view. * * The property is either an array of `DirectiveDef`s or a function which returns the array of * `DirectiveDef`s. The function is necessary to be able to support forward declarations. */ directives?: DirectiveTypesOrFactory | null; /** * Registry of pipes that may be found in this component's view. * * The property is either an array of `PipeDefs`s or a function which returns the array of * `PipeDefs`s. The function is necessary to be able to support forward declarations. */ pipes?: PipeTypesOrFactory | null; }): never; export declare function extractDirectiveDef(type: DirectiveType<any> & ComponentType<any>): DirectiveDefInternal<any> | ComponentDefInternal<any>; export declare function extractPipeDef(type: PipeType<any>): PipeDefInternal<any>; export declare function defineNgModule<T>(def: { type: T; } & Partial<NgModuleDef<T, any, any, any>>): never; /** * Create a directive definition object. * * # Example * ``` * class MyDirective { * // Generated by Angular Template Compiler * // [Symbol] syntax will not be supported by TypeScript until v2.7 * static ngDirectiveDef = defineDirective({ * ... * }); * } * ``` */ export declare const defineDirective: <T>(directiveDefinition: { /** * Directive type, needed to configure the injector. */ type: Type<T>; /** The selectors that will be used to match nodes to this directive. */ selectors: (string | SelectorFlags)[][]; /** * Factory method used to create an instance of directive. */ factory: () => T | ({ 0: T; } & any[]); /** * Static attributes to set on host element. * * Even indices: attribute name * Odd indices: attribute value */ attributes?: string[] | undefined; /** * A map of input names. * * The format is in: `{[actualPropertyName: string]:(string|[string, string])}`. * * Given: * ``` * class MyComponent { * @Input() * publicInput1: string; * * @Input('publicInput2') * declaredInput2: string; * } * ``` * * is described as: * ``` * { * publicInput1: 'publicInput1', * declaredInput2: ['declaredInput2', 'publicInput2'], * } * ``` * * Which the minifier may translate to: * ``` * { * minifiedPublicInput1: 'publicInput1', * minifiedDeclaredInput2: [ 'publicInput2', 'declaredInput2'], * } * ``` * * This allows the render to re-construct the minified, public, and declared names * of properties. * * NOTE: * - Because declared and public name are usually same we only generate the array * `['declared', 'public']` format when they differ. * - The reason why this API and `outputs` API is not the same is that `NgOnChanges` has * inconsistent behavior in that it uses declared names rather than minified or public. For * this reason `NgOnChanges` will be deprecated and removed in future version and this * API will be simplified to be consistent with `output`. */ inputs?: { [P in keyof T]?: string | [string, string] | undefined; } | undefined; /** * A map of output names. * * The format is in: `{[actualPropertyName: string]:string}`. * * Which the minifier may translate to: `{[minifiedPropertyName: string]:string}`. * * This allows the render to re-construct the minified and non-minified names * of properties. */ outputs?: { [P in keyof T]?: string | undefined; } | undefined; /** * A list of optional features to apply. * * See: {@link NgOnChangesFeature}, {@link PublicFeature}, {@link InheritDefinitionFeature} */ features?: DirectiveDefFeature[] | undefined; /** * Function executed by the parent template to allow child directive to apply host bindings. */ hostBindings?: ((directiveIndex: number, elementIndex: number) => void) | undefined; /** * Function to create instances of content queries associated with a given directive. */ contentQueries?: (() => void) | undefined; /** Refreshes content queries associated with directives in a given view */ contentQueriesRefresh?: ((directiveIndex: number, queryIndex: number) => void) | undefined; /** * Defines the name that can be used in the template to assign this directive to a variable. * * See: {@link Directive.exportAs} */ exportAs?: string | undefined; }) => never; /** * Create a pipe definition object. * * # Example * ``` * class MyPipe implements PipeTransform { * // Generated by Angular Template Compiler * static ngPipeDef = definePipe({ * ... * }); * } * ``` * @param pipeDef Pipe definition generated by the compiler */ export declare function definePipe<T>(pipeDef: { /** Name of the pipe. Used for matching pipes in template to pipe defs. */ name: string; /** Pipe class reference. Needed to extract pipe lifecycle hooks. */ type: Type<T>; /** A factory for creating a pipe instance. */ factory: () => T; /** Whether the pipe is pure. */ pure?: boolean; }): never;
the_stack
import { Application, IComponent, events } from '../lib/index'; import * as should from 'should'; import { MockPlugin } from './mock-plugin/components/mockPlugin'; import { MockEvent } from './mock-plugin/events/mockEvent'; declare var afterEach: any; let WAIT_TIME = 1000; let mockBase = process.cwd() + '/test'; let app = new Application(); describe('application test', function () { afterEach(function () { app.state = 0; app.settings = {}; }); describe('#init', function () { it('should init the app instance', function () { app.init({ base: mockBase }); app.state.should.equal(1); // magic number from application.js }); }); describe('#set and get', function () { it('should play the role of normal set and get', function () { should.not.exist(app.get('some undefined key')); let key = 'some defined key', value = 'some value'; app.set(key, value); value.should.equal(app.get(key)); }); it('should return the value if pass just one parameter to the set method', function () { let key = 'some defined key', value = 'some value'; should.not.exist(app.get(key)); app.set(key, value); value.should.equal(app.get(key)); }); }); describe('#enable and disable', function () { it('should play the role of enable and disable', function () { let key = 'some enable key'; app.enabled(key).should.be.false; app.disabled(key).should.be.true; app.enable(key); app.enabled(key).should.be.true; app.disabled(key).should.be.false; app.disable(key); app.enabled(key).should.be.false; app.disabled(key).should.be.true; }); }); describe('#compoent', function () { it('should load the component and fire their lifecircle callback by app.start, app.afterStart, app.stop', function (done: MochaDone) { let startCount = 0, afterStartCount = 0, stopCount = 0; if(require('os').platform() === 'linux') { done(); return; } this.timeout(8000) let mockComponent = { name : 'mockComponent', start: function (cb: Function) { console.log('start invoked'); startCount++; cb(); }, afterStart: function (cb: Function) { console.log('afterStart invoked'); afterStartCount++; cb(); }, stop: function (force: any, cb: Function) { console.log('stop invoked'); stopCount++; cb(); } }; app.init({ base: mockBase }); app.load(mockComponent); app.start(function (err: Error) { should.not.exist(err); }); setTimeout(function () { // wait for after start app.stop(false); setTimeout(function () { // wait for stop startCount.should.equal(1); afterStartCount.should.equal(1); stopCount.should.equal(1); done(); }, WAIT_TIME); }, WAIT_TIME); }); it('should access the component with a name by app.components.name after loaded', function () { let key1 = 'key1', comp1 = new class implements IComponent { name: 'comp1'; content: 'some thing in comp1'; }; let comp2 = { name: 'key2', content: 'some thing in comp2' }; let key3 = 'key3'; let comp3 = function () { return { content: 'some thing in comp3', name: key3 }; }; app.init({ base: mockBase }); app.load(key1, comp1); app.load(comp2); app.load(comp3); app.components.key1.should.eql(comp1); app.components.key2.should.eql(comp2); app.components.key3.should.eql(comp3()); }); it('should ignore duplicated components', function () { let key = 'key'; let comp1 = new class implements IComponent { name: 'comp1'; content: 'some thing in comp1'; }; let comp2 = new class implements IComponent { name: 'comp2'; content: 'some thing in comp2'; }; app.init({ base: mockBase }); app.load(key, comp1); app.load(key, comp2); app.components[key].should.equal(comp1); app.components[key].should.not.equal(comp2); }); }); describe('#filter', function () { it('should add before filter and could fetch it later', function () { let filters = [ function () { console.error('filter1'); }, function () { } ]; app.init({ base: mockBase }); let i, l; for (i = 0, l = filters.length; i < l; i++) { app.before(filters[i]); } let filters2 = app.get('__befores__'); should.exist(filters2); filters2.length.should.equal(filters.length); for (i = 0, l = filters2.length; i < l; i++) { filters2[i].should.equal(filters[i]); } }); it('should add after filter and could fetch it later', function () { let filters = [ function () { console.error('filter1'); }, function () { } ]; app.init({ base: mockBase }); let i, l; for (i = 0, l = filters.length; i < l; i++) { app.after(filters[i]); } let filters2 = app.get('__afters__'); should.exist(filters2); filters2.length.should.equal(filters.length); for (i = 0, l = filters2.length; i < l; i++) { filters2[i].should.equal(filters[i]); } }); it('should add filter and could fetch it from before and after filter later', function () { let filters = [ function () { console.error('filter1'); }, function () { } ]; app.init({ base: mockBase }); let i, l; for (i = 0, l = filters.length; i < l; i++) { app.before(filters[i]); app.after(filters[i]); } let filters2 = app.get('__befores__'); should.exist(filters2); filters2.length.should.equal(filters.length); for (i = 0, l = filters2.length; i < l; i++) { filters2[i].should.equal(filters[i]); } let filters3 = app.get('__afters__'); should.exist(filters3); filters3.length.should.equal(filters.length); for (i = 0, l = filters3.length; i < l; i++) { filters2[i].should.equal(filters[i]); } }); }); describe('#globalFilter', function () { it('should add before global filter and could fetch it later', function () { let filters = [ function () { console.error('global filter1'); }, function () { } ]; app.init({ base: mockBase }); let i, l; for (i = 0, l = filters.length; i < l; i++) { app.globalBefore(filters[i]); } let filters2 = app.get('__globalBefores__'); should.exist(filters2); filters2.length.should.equal(filters.length); for (i = 0, l = filters2.length; i < l; i++) { filters2[i].should.equal(filters[i]); } }); it('should add after global filter and could fetch it later', function () { let filters = [ function () { console.error('filter1'); }, function () { } ]; app.init({ base: mockBase }); let i, l; for (i = 0, l = filters.length; i < l; i++) { app.globalAfter(filters[i]); } let filters2 = app.get('__globalAfters__'); should.exist(filters2); filters2.length.should.equal(filters.length); for (i = 0, l = filters2.length; i < l; i++) { filters2[i].should.equal(filters[i]); } }); it('should add filter and could fetch it from before and after filter later', function () { let filters = [ function () { console.error('filter1'); }, function () { } ]; app.init({ base: mockBase }); let i, l; for (i = 0, l = filters.length; i < l; i++) { app.globalBefore(filters[i]); app.globalAfter(filters[i]); } let filters2 = app.get('__globalBefores__'); should.exist(filters2); filters2.length.should.equal(filters.length); for (i = 0, l = filters2.length; i < l; i++) { filters2[i].should.equal(filters[i]); } let filters3 = app.get('__globalAfters__'); should.exist(filters3); filters3.length.should.equal(filters.length); for (i = 0, l = filters3.length; i < l; i++) { filters2[i].should.equal(filters[i]); } }); }); describe('#configure', function () { it('should execute the code block wtih the right environment', function () { let proCount = 0, devCount = 0; let proEnv = 'production', devEnv = 'development', serverType = 'server'; app.init({ base: mockBase }); app.set('serverType', serverType); app.set('env', proEnv); app.configure(proEnv, serverType, function () { proCount++; }); app.configure(devEnv, serverType, function () { devCount++; }); app.set('env', devEnv); app.configure(proEnv, serverType, function () { proCount++; }); app.configure(devEnv, serverType, function () { devCount++; }); proCount.should.equal(1); devCount.should.equal(1); }); it('should execute the code block wtih the right server', function () { let server1Count = 0, server2Count = 0; let proEnv = 'production', serverType1 = 'server1', serverType2 = 'server2'; app.init({ base: mockBase }); app.set('serverType', serverType1); app.set('env', proEnv); app.configure(proEnv, serverType1, function () { server1Count++; }); app.configure(proEnv, serverType2, function () { server2Count++; }); app.set('serverType', serverType2); app.configure(proEnv, serverType1, function () { server1Count++; }); app.configure(proEnv, serverType2, function () { server2Count++; }); server1Count.should.equal(1); server2Count.should.equal(1); }); }); describe('#route', function () { it('should add route record and could fetch it later', function () { let type1 = 'area', type2 = 'connector'; let func1 = function () { console.log('func1'); }; let func2 = function () { console.log('func2'); }; app.init({ base: mockBase }); app.route(type1, func1); app.route(type2, func2); let routes = app.get('__routes__'); should.exist(routes); func1.should.equal(routes[type1]); func2.should.equal(routes[type2]); }); }); describe('#transaction', function () { it('should execute all conditions and handlers', function () { let conditions = { test1: function (cb: Function) { console.log('condition1'); cb(); }, test2: function (cb: Function) { console.log('condition2'); cb(); } }; let flag = 1; let handlers = { do1: function (cb: Function) { console.log('handler1'); cb(); }, do2: function (cb: Function) { console.log('handler2'); if (flag < 3) { flag++; cb(new Error('error')); } else { cb(); } } }; app.transaction('test', conditions, handlers, 5); }); it('shoud execute conditions with error and do not execute handlers', function () { let conditions = { test1: function (cb: Function) { console.log('condition1'); cb(); }, test2: function (cb: Function) { console.log('condition2'); cb(new Error('error')); }, test3: function (cb: Function) { console.log('condition3'); cb(); } }; let handlers = { do1: function (cb: Function) { console.log('handler1'); cb(); }, do2: function (cb: Function) { console.log('handler2'); cb(); } }; app.transaction('test', conditions, handlers); }); }); describe('#add and remove servers', function () { it('should add servers and emit event and fetch the new server info by get methods', function (done: MochaDone) { let newServers = [ { id: 'connector-server-1', serverType: 'connecctor', host: '127.0.0.1', port: 1234, clientPort: 3000, frontend: true }, { id: 'area-server-1', serverType: 'area', host: '127.0.0.1', port: 2234 } ]; app.init({ base: mockBase }); app.event.on(events.ADD_SERVERS, function (servers: Array<{ [key: string]: any }>) { // check event args newServers.should.eql(servers); // check servers let curServers = app.getServers(); should.exist(curServers); let item, i, l; for (i = 0, l = newServers.length; i < l; i++) { item = newServers[i]; item.should.eql(curServers[item.id]); } // check get server by id for (i = 0, l = newServers.length; i < l; i++) { item = newServers[i]; item.should.eql(app.getServerById(item.id)); } // check server types let types = []; for (i = 0, l = newServers.length; i < l; i++) { item = newServers[i]; if (types.indexOf(item.serverType) < 0) { types.push(item.serverType); } } let types2 = app.getServerTypes(); types.length.should.equal(types2.length); for (i = 0, l = types.length; i < l; i++) { types2.should.containEql(types[i]); } // check server type list let slist; for (i = 0, l = newServers.length; i < l; i++) { item = newServers[i]; slist = app.getServersByType(item.serverType); should.exist(slist); contains(slist, item).should.be.true; } done(); }); app.addServers(newServers); app.event.removeAllListeners() }); it('should remove server info and emit event', function (done: MochaDone) { let newServers = [ { id: 'connector-server-1', serverType: 'connecctor', host: '127.0.0.1', port: 1234, clientPort: 3000, frontend: true }, { id: 'area-server-1', serverType: 'area', host: '127.0.0.1', port: 2234 }, { id: 'path-server-1', serverType: 'path', host: '127.0.0.1', port: 2235 } ]; let destServers = [ { id: 'connector-server-1', serverType: 'connecctor', host: '127.0.0.1', port: 1234, clientPort: 3000, frontend: true }, { id: 'path-server-1', serverType: 'path', host: '127.0.0.1', port: 2235 } ]; let delIds = ['area-server-1']; let addCount = 0; let delCount = 0; app.init({ base: mockBase }); app.event.on(events.ADD_SERVERS, function (servers: Array<{ [key: string]: any }>) { // check event args newServers.should.eql(servers); addCount++; }); app.event.on(events.REMOVE_SERVERS, function (ids: Array<string>) { delIds.should.eql(ids); // check servers let curServers = app.getServers(); should.exist(curServers); let item, i, l; for (i = 0, l = destServers.length; i < l; i++) { item = destServers[i]; item.should.eql(curServers[item.id]); } // check get server by id for (i = 0, l = destServers.length; i < l; i++) { item = destServers[i]; item.should.eql(app.getServerById(item.id)); } // check server types // NOTICE: server types would not clear when remove server from app let types = []; for (i = 0, l = newServers.length; i < l; i++) { item = newServers[i]; if (types.indexOf(item.serverType) < 0) { types.push(item.serverType); } } let types2 = app.getServerTypes(); types.length.should.equal(types2.length); for (i = 0, l = types.length; i < l; i++) { types2.should.containEql(types[i]); } // check server type list let slist; for (i = 0, l = destServers.length; i < l; i++) { item = destServers[i]; slist = app.getServersByType(item.serverType); should.exist(slist); contains(slist, item).should.be.true; } app.event.removeAllListeners() done(); }); app.addServers(newServers); app.removeServers(delIds); }); }); describe('#beforeStopHook', function () { it('should be called before application stopped.', function (done: MochaDone) { if(require('os').platform() === 'linux') { done(); return; } let count = 0; this.timeout(8888) app.init({ base: mockBase }); app.beforeStopHook(function () { count++; }); app.start(function (err: Error) { should.not.exist(err); }); setTimeout(function () { // wait for after start app.stop(false); setTimeout(function () { // wait for stop count.should.equal(1); done(); }, WAIT_TIME); }, WAIT_TIME); }); }); describe('#use', function () { it('should exist plugin component and event', function (done: MochaDone) { let plugin = { name: 'mock-plugin', components: [MockPlugin], events: [MockEvent] }; let opts = {}; app.use(plugin, opts); should.exist(app.event.listeners('bind_session')); should.exist(app.components.mockPlugin); done(); }); }); }); let contains = function (slist: Array<{ [key: string]: any }>, sinfo: { [key: string]: any }) { for (let i = 0, l = slist.length; i < l; i++) { if (slist[i].id === sinfo.id) { return true; } } return false; };
the_stack
import { Subscription } from 'rxjs'; import { Component, Input, OnDestroy, OnInit } from '@angular/core'; // Application specific imports. import { Message } from 'src/app/models/message.model'; import { MessageService } from 'src/app/services/message.service'; import { Endpoint } from '../../../endpoints/models/endpoint.model'; import { EndpointService } from '../../../endpoints/services/endpoint.service'; import { CrudifyService } from '../../services/crudify.service'; /** * Endpoint model class, for allowing user to select which endpoints * he or she wants to include in the generated frontend. */ class EndpointEx extends Endpoint { /** * Whether or not endpoint has been selected. */ selected: boolean; } /** * Crudifier component for generating a frontend from * meta information about backend. */ @Component({ selector: 'app-crudifier-frontend-extra', templateUrl: './crudifier-frontend-extra.component.html', styleUrls: ['./crudifier-frontend-extra.component.scss'] }) export class CrudifierFrontendExtraComponent implements OnInit, OnDestroy { // Used to subscribe to messages sent by other components. private subscription: Subscription; /** * Template user selected */ @Input() public template: string; /** * Columns to display in endpoints table. */ public displayedColumns: string[] = [ 'selected', 'path', 'verb', ]; /** * Endpoints as retrieved from backend. */ public endpoints: EndpointEx[]; /** * True if advanced settings shoulkd be shown. */ public advanced = false; /** * List of modules we found in backend. */ public modules: string[] = []; /** * Custom args associates with template. */ public custom: any = null; /** * Additional args as passed in during crudification. */ public args: any = {}; /** * Creates an instance of your component. * * @param messageService Needed to subscribe to messages published by other components * @param endpointService Needed to retrieve templates, meta information, and actually generate frontend */ constructor( private messageService: MessageService, private endpointService: EndpointService, private crudifyService: CrudifyService) { } /** * Implementation of OnInit. */ public ngOnInit() { // Retrieving custom template arguments. this.crudifyService.templateCustomArgs(this.template).subscribe((res: any) => { // Assigning model and trying to find sane default values for them. this.custom = res; for (const idx in res) { if (Array.isArray(res[idx])) { this.args[idx] = res[idx][0].value; } } }); // Making sure we usbscribe to the 'generate' message. this.subscription = this.messageService.subscriber().subscribe((msg: Message) => { if (msg.name === 'app.generator.generate-frontend') { this.generate( msg.content.template, msg.content.name, msg.content.copyright, msg.content.apiUrl, msg.content.frontendUrl, msg.content.email, msg.content.deployLocally); } }); // Retrieving endpoints from backend. this.endpointService.endpoints().subscribe((endpoints: Endpoint[]) => { // Assigning result to model. this.endpoints = endpoints .filter(x => !x.path.startsWith('magic/system/') && !x.path.startsWith('magic/modules/magic/')) .filter(x => x.type === 'crud-count' || x.type === 'crud-delete' || x.type === 'crud-read' || x.type === 'crud-create' || x.type === 'crud-update') .map(x => { return { path: x.path, verb: x.verb, consumes: x.consumes, produces: x.produces, input: x.input, output: x.output, array: x.array, auth: x.auth, type: x.type, description: x.description, selected: true, }; }); // Assigning modules to model. const modules: string[] = []; for (const idx of this.endpoints) { let moduleName = idx.path.substr('magic/modules/'.length); moduleName = moduleName.substr(0, moduleName.indexOf('/')); if (modules.indexOf(moduleName) === -1) { modules.push(moduleName); } } this.modules = modules; }); } /** * Implementation of OnDestroy. */ public ngOnDestroy() { // Making sure we unsubscribe to messages transmitted by other components. this.subscription.unsubscribe(); } /** * Returns tooltip for generate button. */ public getGenerateTooltip() { if (!this.endpoints) { return ''; } let componentCount = this.endpoints.filter(x => x.selected && x.path.endsWith('-count')).length; let endpointCount = this.endpoints.filter(x => x.selected).length; return `Generate ${componentCount} components wrapping ${endpointCount} HTTP endpoints`; } /** * Returns the names of all component that will be generated. */ public getComponents() { return this.endpoints .filter(x => x.type === 'crud-count') .map(x => { const componentName = x.path.substr(14); return componentName.substr(0, componentName.length - 6); }); } /** * Returns the number of selected endpoints. */ public selectedEndpoints() { return this.endpoints.filter(x => x.selected).length; } /** * Invoked when the user clicks a module. * * @param module Name of module */ public moduleClicked(module: string) { // Toggling the selected value of all endpoints encapsulated by module. const moduleEndpoints = this.endpoints.filter(x => x.path.startsWith('magic/modules/' + module + '/')); if (moduleEndpoints.filter(x => x.selected).length === moduleEndpoints.length) { for (const idx of moduleEndpoints) { idx.selected = false; } } else { for (const idx of moduleEndpoints) { let toBeSelected = true; for (var idx2 of moduleEndpoints.filter(x => x.selected && x.verb === idx.verb)) { const split1 = idx2.path.split('/'); const split2 = idx.path.split('/'); if (split1[split1.length - 1] === split2[split2.length - 1]) { toBeSelected = false; } } idx.selected = toBeSelected; } } } /** * Invoked when a component is selected or de-selected for being generated. * * @param component Name of component that was clicked */ public componentClicked(component: string) { // Finding all relevant components. const components = this.endpoints .filter(x => x.path.endsWith('/' + component) || x.path.endsWith('/' + component + '-count')); // Figuring out if we should select or de-select component. const shouldSelect = components.filter(x => !x.selected).length > 0; // Looping through all components and changing their selected state according to above logic. for (const idx of components) { idx.selected = shouldSelect; } } /** * Invoked to check if the specified module to selected or not, as * in all endpoints have been selected for crudification. * * @param module What module to check for */ public moduleSelected(module: string) { const moduleEndpoints = this.endpoints.filter(x => x.path.startsWith('magic/modules/' + module + '/')); if (moduleEndpoints.filter(x => x.selected).length === moduleEndpoints.length) { return true; } else { return false; } } /** * Returns true if component is selected. * * @param component Name of component to check for */ public componentSelected(component: string) { return this.endpoints .filter(x => x.selected) .filter(x => { return x.verb === 'get' && x.type === 'crud-count' && (x.path == 'magic/modules/' + component + '-count'); }).length === 1; } /* * Private helper methods. */ /* * Invoked when user wants to generate a frontend of some sort. */ private generate( template: string, name: string, copyright: string, apiUrl: string, frontendUrl: string, email: string, deployLocally: boolean) { // Making sure API URL ends with exactly one slash '/'. while (apiUrl.endsWith('/')) { apiUrl = apiUrl.substr(0, apiUrl.length - 1); } // Invoking backend to actually generate the specified frontend. const svcModel = this.createServiceModel(this.endpoints.filter(x => x.selected)); this.crudifyService.generate( template, apiUrl + '/', frontendUrl, email, name, copyright === '' ? 'Automatically generated by Magic' : copyright, svcModel, deployLocally, this.args, () => { // Publishing message to subscribers that '/modules/' folder changed. this.messageService.sendMessage({ name: deployLocally ? 'magic.crudifier.frontend-generated-locally' : 'magic.crudifier.frontend-generated' }); }); } /* * Creates the requires HTTP service model for generating frontend * from frontend data model. */ private createServiceModel(endpoints: EndpointEx[]) { const result: any[] = []; for (const idx of endpoints) { const tmp = { auth: idx.auth, description: idx.description, path: idx.path, type: idx.type, verb: idx.verb, input: [], output: [], }; if (idx.input && idx.input.length > 0) { // Sorting input fields in order of lookup, string, date, the rest ... idx.input.sort((lhs, rhs) => { if (lhs.name.toLowerCase() === 'name' && rhs.name.toLowerCase() !== 'name') { return -1; } if (lhs.name.toLowerCase() !== 'name' && rhs.name.toLowerCase() === 'name') { return 1; } if (lhs.name.toLowerCase() === 'name' && rhs.name.toLowerCase() === 'name') { return 0; } if (lhs.name.toLowerCase().indexOf('name') >= 0 && lhs.name.indexOf('.') === -1 && (rhs.name.toLowerCase().indexOf('name') === -1 || rhs.name.indexOf('.') >= 0)) { return -1; } if (rhs.name.toLowerCase().indexOf('name') >= 0 && rhs.name.indexOf('.') === -1 && (lhs.name.toLowerCase().indexOf('name') === -1 || lhs.name.indexOf('.') >= 0)) { return 1; } if (lhs.lookup && !rhs.lookup) { return -1; } if (!lhs.lookup && rhs.lookup) { return 1; } if (lhs.lookup && rhs.lookup) { return 0; } if (lhs.type === 'string' && rhs.type !== 'string') { return -1; } if (lhs.type !== 'string' && rhs.type === 'string') { return 1; } if (lhs.type === 'string' && rhs.type === 'string') { return 0; } if (lhs.type === 'date' && rhs.type !== 'date') { return -1; } if (lhs.type !== 'date' && rhs.type === 'date') { return 1; } if (lhs.type === 'date' && rhs.type === 'date') { return 0; } return 0; }); for (const idxInput of idx.input) { const cur: any = { name: idxInput.name, type: idxInput.type, }; if (idxInput.lookup) { cur.lookup = idxInput.lookup; cur.lookup.table = cur.lookup.table.replace('dbo.', '').toLowerCase(); cur.lookup.service = idx.path.substr(14); cur.lookup.service = cur.lookup.service.substr(0, cur.lookup.service.indexOf('/')) + '.' + cur.lookup.table; while (cur.lookup.service.indexOf('.') > 0) { cur.lookup.service = cur.lookup.service.replace('.', '_'); } } tmp.input.push(cur); } } if (idx.output && idx.output.length > 0) { // Sorting input fields in order of lookup, string, date, the rest ... idx.output.sort((lhs, rhs) => { if (lhs.name.toLowerCase() === 'name' && rhs.name.toLowerCase() !== 'name') { return -1; } if (lhs.name.toLowerCase() !== 'name' && rhs.name.toLowerCase() === 'name') { return 1; } if (lhs.name.toLowerCase() === 'name' && rhs.name.toLowerCase() === 'name') { return 0; } if (lhs.name.toLowerCase().indexOf('name') >= 0 && lhs.name.indexOf('.') === -1 && (rhs.name.toLowerCase().indexOf('name') === -1 || rhs.name.indexOf('.') >= 0)) { return -1; } if (rhs.name.toLowerCase().indexOf('name') >= 0 && rhs.name.indexOf('.') === -1 && (lhs.name.toLowerCase().indexOf('name') === -1 || lhs.name.indexOf('.') >= 0)) { return 1; } if (lhs.lookup && !rhs.lookup) { return -1; } if (!lhs.lookup && rhs.lookup) { return 1; } if (lhs.lookup && rhs.lookup) { return 0; } if (idx.type === 'crud-read') { // CRUD read endpoint type, making sure linked fields comes before others. let lhsIsLinked = false; if (lhs.name.indexOf('.') > 0) { const firstSplit = lhs.name.split('.')[0]; const urlSplit = idx.path.split('/'); if (firstSplit !== urlSplit[urlSplit.length]) { lhsIsLinked = true; } } let rhsIsLinked = false; if (rhs.name.indexOf('.') > 0) { const firstSplit = rhs.name.split('.')[0]; const urlSplit = idx.path.split('/'); if (firstSplit !== urlSplit[urlSplit.length]) { rhsIsLinked = true; } } if (lhsIsLinked && !rhsIsLinked) { return -1; } if (!lhsIsLinked && rhsIsLinked) { return 1; } if (lhsIsLinked && rhsIsLinked) { return 0; } } if (lhs.type === 'string' && rhs.type !== 'string') { return -1; } if (lhs.type !== 'string' && rhs.type === 'string') { return 1; } if (lhs.type === 'string' && rhs.type === 'string') { return 0; } if (lhs.type === 'date' && rhs.type !== 'date') { return -1; } if (lhs.type !== 'date' && rhs.type === 'date') { return 1; } if (lhs.type === 'date' && rhs.type === 'date') { return 0; } return 0; }); for (const idxOutput of idx.output) { const cur: any = { name: idxOutput.name, type: idxOutput.type || tmp.input[idxOutput.name + '.eq'], }; if (idxOutput.lookup) { cur.lookup = idxOutput.lookup; cur.lookup.table = cur.lookup.table.replace('dbo.', '').toLowerCase(); cur.lookup.service = idx.path.substr(14); cur.lookup.service = cur.lookup.service.substr(0, cur.lookup.service.indexOf('/')) + '.' + cur.lookup.table; while (cur.lookup.service.indexOf('.') > 0) { cur.lookup.service = cur.lookup.service.replace('.', '_'); } } tmp.output.push(cur); } } result.push(tmp); } return result; } }
the_stack
import * as fs from '@nativescript/core/file-system'; // << file-system-require import * as TKUnit from '../tk-unit'; import * as appModule from '@nativescript/core/application'; import { isIOS, Device, platformNames } from '@nativescript/core'; export var testPathNormalize = function () { // >> file-system-normalize var documents = fs.knownFolders.documents(); var testPath = '///test.txt'; // Get a normalized path such as <folder.path>/test.txt from <folder.path>///test.txt var normalizedPath = fs.path.normalize(documents.path + testPath); // >> (hide) var expected = documents.path + '/test.txt'; TKUnit.assert(normalizedPath === expected); // << (hide) // << file-system-normalize }; export var testPathJoin = function () { // >> file-system-multiple-args var documents = fs.knownFolders.documents(); // Generate a path like <documents.path>/myFiles/test.txt var path = fs.path.join(documents.path, 'myFiles', 'test.txt'); // >> (hide) var expected = documents.path + '/myFiles/test.txt'; TKUnit.assert(path === expected); // << (hide) // << file-system-multiple-args }; export var testPathSeparator = function () { // >> file-system-separator // An OS dependent path separator, "\" or "/". var separator = fs.path.separator; // >> (hide) var expected = '/'; TKUnit.assert(separator === expected); // << (hide) // << file-system-separator }; export var testFileFromPath = function () { // >> file-system-create var documents = fs.knownFolders.documents(); var path = fs.path.join(documents.path, 'FileFromPath.txt'); var file = fs.File.fromPath(path); // Writing text to the file. file.writeText('Something').then( function () { // Succeeded writing to the file. // >> (hide) file.readText().then( function (content) { TKUnit.assert(content === 'Something', 'File read/write not working.'); file.remove(); }, function (error) { TKUnit.assert(false, 'Failed to read/write text'); //console.dir(error); } ); // << (hide) }, function (error) { // Failed to write to the file. // >> (hide) TKUnit.assert(false, 'Failed to read/write text'); //console.dir(error); // << (hide) } ); // << file-system-create }; export var testFolderFromPath = function () { // >> file-system-create-folder var path = fs.path.join(fs.knownFolders.documents().path, 'music'); var folder = fs.Folder.fromPath(path); // >> (hide) TKUnit.assert(<any>folder, 'Folder.getFolder API not working.'); TKUnit.assert(fs.Folder.exists(folder.path), 'Folder.getFolder API not working.'); folder.remove(); // << (hide) // << file-system-create-folder }; export var testFileWrite = function () { // >> file-system-write-string var documents = fs.knownFolders.documents(); var file = documents.getFile('Test_Write.txt'); // Writing text to the file. file.writeText('Something').then( function () { // Succeeded writing to the file. // >> (hide) file.readText().then( function (content) { TKUnit.assert(content === 'Something', 'File read/write not working.'); file.remove(); }, function (error) { TKUnit.assert(false, 'Failed to read/write text'); //console.dir(error); } ); // << (hide) }, function (error) { // Failed to write to the file. // >> (hide) TKUnit.assert(false, 'Failed to read/write text'); //console.dir(error); // << (hide) } ); // << file-system-write-string }; export var testGetFile = function () { // >> file-system-create-file var documents = fs.knownFolders.documents(); var file = documents.getFile('NewFileToCreate.txt'); // >> (hide) TKUnit.assert(<any>file, 'File.getFile API not working.'); TKUnit.assert(fs.File.exists(file.path), 'File.getFile API not working.'); file.remove(); // << (hide) // << file-system-create-file }; export var testGetFolder = function () { // >> file-system-get-folder var documents = fs.knownFolders.documents(); var folder = documents.getFolder('NewFolderToCreate'); // >> (hide) TKUnit.assert(<any>folder, 'Folder.getFolder API not working.'); TKUnit.assert(fs.Folder.exists(folder.path), 'Folder.getFolder API not working.'); folder.remove(); // << (hide) // << file-system-get-folder }; export var testFileRead = function () { // >> file-system-example-text var documents = fs.knownFolders.documents(); var myFile = documents.getFile('Test_Write.txt'); var written: boolean; // Writing text to the file. myFile.writeText('Something').then( function () { // Succeeded writing to the file. // Getting back the contents of the file. myFile.readText().then( function (content) { // Successfully read the file's content. // >> (hide) written = content === 'Something'; TKUnit.assert(written, 'File read/write not working.'); myFile.remove(); // << (hide) }, function (error) { // Failed to read from the file. // >> (hide) TKUnit.assert(false, 'Failed to read/write text'); //console.dir(error); // << (hide) } ); }, function (error) { // Failed to write to the file. // >> (hide) TKUnit.assert(false, 'Failed to read/write text'); //console.dir(error); // << (hide) } ); // << file-system-example-text }; export var testFileReadWriteBinary = function () { // >> file-system-read-binary var fileName = 'logo.png'; var error; var sourceFile = fs.File.fromPath(__dirname + '/assets/' + fileName); var destinationFile = fs.knownFolders.documents().getFile(fileName); var source = sourceFile.readSync((e) => { error = e; }); destinationFile.writeSync(source, (e) => { error = e; }); // >> (hide) var destination = destinationFile.readSync((e) => { error = e; }); TKUnit.assertNull(error); if (Device.os === platformNames.ios) { TKUnit.assertTrue(source.isEqualToData(destination)); } else { TKUnit.assertEqual(new java.io.File(sourceFile.path).length(), new java.io.File(destinationFile.path).length()); } destinationFile.removeSync(); // << (hide) // << file-system-read-binary }; export var testFileReadWriteBinaryAsync = function () { // >> file-system-read-binary-async var fileName = 'logo.png'; var sourceFile = fs.File.fromPath(__dirname + '/assets/' + fileName); var destinationFile = fs.knownFolders.documents().getFile(fileName); // Read the file sourceFile.read().then( function (source) { // Succeeded in reading the file // >> (hide) destinationFile.write(source).then( function () { // Succeded in writing the file destinationFile.read().then( function (destination) { if (Device.os === platformNames.ios) { TKUnit.assertTrue(source.isEqualToData(destination)); } else { TKUnit.assertEqual(new java.io.File(sourceFile.path).length(), new java.io.File(destinationFile.path).length()); } destinationFile.removeSync(); }, function (error) { TKUnit.assert(false, 'Failed to read destination binary async'); } ); }, function (error) { // Failed to write the file. TKUnit.assert(false, 'Failed to write binary async'); } ); // << (hide) }, function (error) { // Failed to read the file. // >> (hide) TKUnit.assert(false, 'Failed to read binary async'); // << (hide) } ); // << file-system-read-binary-async }; export var testGetKnownFolders = function () { // >> file-system-known-folders // Getting the application's 'documents' folder. var documents = fs.knownFolders.documents(); // >> (hide) TKUnit.assert(<any>documents, 'Could not retrieve the Documents known folder.'); TKUnit.assert(documents.isKnown, 'The Documents folder should have its isKnown property set to true.'); // << (hide) // Getting the application's 'temp' folder. var temp = fs.knownFolders.temp(); // >> (hide) TKUnit.assert(<any>temp, 'Could not retrieve the Temporary known folder.'); TKUnit.assert(temp.isKnown, 'The Temporary folder should have its isKnown property set to true.'); // << (hide) // << file-system-known-folders }; function _testIOSSpecificKnownFolder(knownFolderName: string) { let knownFolder: fs.Folder; let createdFile: fs.File; let testFunc = function testFunc() { knownFolder = fs.knownFolders.ios[knownFolderName](); if (knownFolder) { createdFile = knownFolder.getFile('createdFile'); createdFile.writeTextSync('some text'); } }; if (isIOS) { testFunc(); if (knownFolder) { TKUnit.assertTrue(knownFolder.isKnown, `The ${knownFolderName} folder should have its "isKnown" property set to true.`); TKUnit.assertNotNull(createdFile, `Could not create a new file in the ${knownFolderName} known folder.`); TKUnit.assertTrue(fs.File.exists(createdFile.path), `Could not create a new file in the ${knownFolderName} known folder.`); TKUnit.assertEqual(createdFile.readTextSync(), 'some text', `The contents of the new file created in the ${knownFolderName} known folder are not as expected.`); } } else { TKUnit.assertThrows(testFunc, `Trying to retrieve the ${knownFolderName} known folder on a platform different from iOS should throw!`, `The "${knownFolderName}" known folder is available on iOS only!`); } } export var testIOSSpecificKnownFolders = function () { _testIOSSpecificKnownFolder('library'); _testIOSSpecificKnownFolder('developer'); _testIOSSpecificKnownFolder('desktop'); _testIOSSpecificKnownFolder('downloads'); _testIOSSpecificKnownFolder('movies'); _testIOSSpecificKnownFolder('music'); _testIOSSpecificKnownFolder('pictures'); _testIOSSpecificKnownFolder('sharedPublic'); }; export var testGetEntities = function () { // >> file-system-folders-content var documents = fs.knownFolders.documents(); // >> (hide) var file = documents.getFile('Test.txt'); var file1 = documents.getFile('Test1.txt'); var fileFound, file1Found; // IMPORTANT: console.log is mocked to make the snippet pretty. var globalConsole = console; var console = { log: function (file) { if (file === 'Test.txt') { fileFound = true; } else if (file === 'Test1.txt') { file1Found = true; } }, }; // << (hide) documents.getEntities().then( function (entities) { // entities is array with the document's files and folders. entities.forEach(function (entity) { console.log(entity.name); }); // >> (hide) TKUnit.assert(fileFound, 'Failed to enumerate Test.txt'); TKUnit.assert(file1Found, 'Failed to enumerate Test1.txt'); file.remove(); file1.remove(); // << (hide) }, function (error) { // Failed to obtain folder's contents. // globalConsole.error(error.message); } ); // << file-system-folders-content }; export var testEnumEntities = function () { // >> file-system-enum-content var documents = fs.knownFolders.documents(); // >> (hide) var file = documents.getFile('Test.txt'); var file1 = documents.getFile('Test1.txt'); var testFolder = documents.getFolder('testFolder'); var fileFound = false; var file1Found = false; var testFolderFound = false; var console = { log: function (file) { if (file === 'Test.txt') { fileFound = true; } else if (file === 'Test1.txt') { file1Found = true; } else if (file === 'testFolder') { testFolderFound = true; } }, }; // << (hide) documents.eachEntity(function (entity) { console.log(entity.name); // Return true to continue, or return false to stop the iteration. return true; }); // >> (hide) TKUnit.assert(fileFound, 'Failed to enumerate Test.txt'); TKUnit.assert(file1Found, 'Failed to enumerate Test1.txt'); TKUnit.assert(testFolderFound, 'Failed to enumerate testFolder'); file.remove(); file1.remove(); testFolder.remove(); // << (hide) // << file-system-enum-content }; export var testGetParent = function () { // >> file-system-parent var documents = fs.knownFolders.documents(); var file = documents.getFile('Test.txt'); // >> (hide) TKUnit.assert(<any>file, 'Failed to create file in the Documents folder.'); // << (hide) // The parent folder of the file would be the documents folder. var parent = file.parent; // >> (hide) TKUnit.assert(documents === parent, 'The parent folder should be the Documents folder.'); file.remove(); // << (hide) // << file-system-parent }; export var testFileNameExtension = function () { // >> file-system-extension var documents = fs.knownFolders.documents(); var file = documents.getFile('Test.txt'); // Getting the file name "Test.txt". var fileName = file.name; // Getting the file extension ".txt". var fileExtension = file.extension; // >> (hide) TKUnit.assert(fileName === 'Test.txt', 'Wrong file name.'); TKUnit.assert(fileExtension === '.txt', 'Wrong extension.'); file.remove(); // << (hide) // << file-system-extension }; export var testFileExists = function () { // >> file-system-fileexists var documents = fs.knownFolders.documents(); var filePath = fs.path.join(documents.path, 'Test.txt'); var exists = fs.File.exists(filePath); // >> (hide) TKUnit.assert(!exists, 'File.exists API not working.'); var file = documents.getFile('Test.txt'); exists = fs.File.exists(file.path); TKUnit.assert(exists, 'File.exists API not working.'); file.remove(); // << (hide) // << file-system-fileexists }; export var testFolderExists = function () { // >> file-system-folderexists var documents = fs.knownFolders.documents(); var exists = fs.Folder.exists(documents.path); // >> (hide) TKUnit.assert(exists, 'Folder.exists API not working.'); exists = fs.Folder.exists(documents.path + '_'); TKUnit.assert(!exists, 'Folder.exists API not working.'); // << (hide) // << file-system-folderexists }; export var testContainsFile = function () { var folder = fs.knownFolders.documents(); var file = folder.getFile('Test.txt'); var contains = folder.contains('Test.txt'); TKUnit.assert(contains, 'Folder.contains API not working.'); contains = folder.contains('Test_xxx.txt'); TKUnit.assert(!contains, 'Folder.contains API not working.'); file.remove(); }; export var testFileRename = function () { // >> file-system-renaming var documents = fs.knownFolders.documents(); var file = documents.getFile('Test.txt'); file.rename('Test_renamed.txt').then( function (result) { // Successfully Renamed. // >> (hide) TKUnit.assert(file.name === 'Test_renamed.txt', 'File.rename API not working.'); file.remove(); documents.getFile('Test.txt').remove(); // << (hide) }, function (error) { // Failed to rename the file. // >> (hide) TKUnit.assert(false, 'Failed to rename file'); // << (hide) } ); // << file-system-renaming }; export var testFolderRename = function () { // >> file-system-renaming-folder var folder = fs.knownFolders.documents(); var myFolder = folder.getFolder('Test__'); myFolder.rename('Something').then( function (result) { // Successfully Renamed. // >> (hide) TKUnit.assert(myFolder.name === 'Something', 'Folder.rename API not working.'); myFolder.remove(); folder.getFolder('Test__').remove(); // << (hide) }, function (error) { // Failed to rename the folder. // >> (hide) TKUnit.assert(false, 'Folder.rename API not working.'); // << (hide) } ); // << file-system-renaming-folder }; export var testFileRemove = function () { // >> file-system-remove-file var documents = fs.knownFolders.documents(); var file = documents.getFile('AFileToRemove.txt'); file.remove().then( function (result) { // Success removing the file. // >> (hide) TKUnit.assert(!fs.File.exists(file.path)); // << (hide) }, function (error) { // Failed to remove the file. // >> (hide) TKUnit.assert(false, 'File.remove API not working.'); // << (hide) } ); // << file-system-remove-file }; export var testFolderRemove = function () { // >> file-system-remove-folder var documents = fs.knownFolders.documents(); var file = documents.getFolder('AFolderToRemove'); // Remove a folder and recursively its content. file.remove().then( function (result) { // Success removing the folder. // >> (hide) TKUnit.assert(!fs.File.exists(file.path)); // << (hide) }, function (error) { // Failed to remove the folder. // >> (hide) TKUnit.assert(false, 'File.remove API not working.'); // << (hide) } ); // << file-system-remove-folder }; export var testFolderClear = function () { // >> file-system-clear-folder var documents = fs.knownFolders.documents(); var folder = documents.getFolder('testFolderEmpty'); // >> (hide) folder.getFile('Test1.txt'); folder.getFile('Test2.txt'); var subfolder = folder.getFolder('subfolder'); var emptied; // << (hide) folder.clear().then( function () { // Successfully cleared the folder. // >> (hide) emptied = true; // << (hide) }, function (error) { // Failed to clear the folder. // >> (hide) TKUnit.assert(false, error.message); // << (hide) } ); // >> (hide) folder.getEntities().then(function (entities) { TKUnit.assertEqual(entities.length, 0, `${entities.length} entities left after clearing a folder.`); folder.remove(); }); // << (hide) // << file-system-clear-folder }; // misc export var testKnownFolderRename = function () { // You can rename known folders in android - so skip this test. if (!appModule.android) { var folder = fs.knownFolders.documents(); folder.rename('Something').then( function (result) { TKUnit.assert(false, 'Known folders should not be renamed.'); }, function (error) { TKUnit.assert(true); } ); } }; export function testKnownFolderRemove(done) { var result; var knownFolder = fs.knownFolders.temp(); knownFolder.remove().then( function () { done(new Error('Remove known folder should resolve as error.')); }, function (error) { done(null); } ); } export function test_FSEntity_Properties() { var documents = fs.knownFolders.documents(); var file = documents.getFile('Test_File.txt'); TKUnit.assert(file.extension === '.txt', 'FileEntity.extension not working.'); TKUnit.assert(file.isLocked === false, 'FileEntity.isLocked not working.'); TKUnit.assert(file.lastModified instanceof Date, 'FileEntity.lastModified not working.'); TKUnit.assert(file.size === 0, 'FileEntity.size not working.'); TKUnit.assert(file.name === 'Test_File.txt', 'FileEntity.name not working.'); TKUnit.assert(file.parent === documents, 'FileEntity.parent not working.'); file.remove(); } export function test_FileSize(done) { var file = fs.knownFolders.documents().getFile('Test_File_Size.txt'); file .writeText('Hello World!') .then(() => { TKUnit.assert(file.size === 'Hello World!'.length); return file.remove(); }) .then(() => done()) .catch(done); } export function test_UnlockAfterWrite(done) { var file = fs.knownFolders.documents().getFile('Test_File_Lock.txt'); file .writeText('Hello World!') .then(() => { return file.readText(); }) .then((value) => { TKUnit.assert(value === 'Hello World!'); return file.remove(); }) .then(() => done()) .catch(done); } export function test_CreateParentOnNewFile(done) { var documentsFolderName = fs.knownFolders.documents().path; var tempFileName = fs.path.join(documentsFolderName, 'folder1', 'folder2', 'Test_File_Create_Parent.txt'); var file = fs.File.fromPath(tempFileName); file .writeText('Hello World!') .then(() => { return fs.knownFolders.documents().getFolder('folder1').remove(); }) .then(() => done()) .catch(done); } export function test_FolderClear_RemovesEmptySubfolders(done) { let documents = fs.knownFolders.documents(); let rootFolder = documents.getFolder('rootFolder'); let emptySubfolder = rootFolder.getFolder('emptySubfolder'); TKUnit.assertTrue(fs.Folder.exists(emptySubfolder.path), 'emptySubfolder should exist before parent folder is cleared.'); rootFolder .clear() .then(() => { TKUnit.assertFalse(fs.File.exists(emptySubfolder.path), 'emptySubfolder should not exist after parent folder was cleared.'); rootFolder.remove(); done(); }) .catch(done); }
the_stack
import { QueryFilters, Updater, hashQueryKey, noop, parseFilterArgs, parseQueryArgs, partialMatchKey, hashQueryKeyByOptions, MutationFilters, } from './utils' import type { DefaultOptions, FetchInfiniteQueryOptions, FetchQueryOptions, InfiniteData, InvalidateOptions, InvalidateQueryFilters, MutationKey, MutationObserverOptions, MutationOptions, QueryFunction, QueryKey, QueryObserverOptions, QueryOptions, RefetchOptions, RefetchQueryFilters, ResetOptions, ResetQueryFilters, } from './types' import type { QueryState, SetDataOptions } from './query' import { QueryCache } from './queryCache' import { MutationCache } from './mutationCache' import { focusManager } from './focusManager' import { onlineManager } from './onlineManager' import { notifyManager } from './notifyManager' import { CancelOptions } from './retryer' import { infiniteQueryBehavior } from './infiniteQueryBehavior' // TYPES interface QueryClientConfig { queryCache?: QueryCache mutationCache?: MutationCache defaultOptions?: DefaultOptions } interface QueryDefaults { queryKey: QueryKey defaultOptions: QueryOptions<any, any, any> } interface MutationDefaults { mutationKey: MutationKey defaultOptions: MutationOptions<any, any, any, any> } // CLASS export class QueryClient { private queryCache: QueryCache private mutationCache: MutationCache private defaultOptions: DefaultOptions private queryDefaults: QueryDefaults[] private mutationDefaults: MutationDefaults[] private unsubscribeFocus?: () => void private unsubscribeOnline?: () => void constructor(config: QueryClientConfig = {}) { this.queryCache = config.queryCache || new QueryCache() this.mutationCache = config.mutationCache || new MutationCache() this.defaultOptions = config.defaultOptions || {} this.queryDefaults = [] this.mutationDefaults = [] } mount(): void { this.unsubscribeFocus = focusManager.subscribe(() => { if (focusManager.isFocused() && onlineManager.isOnline()) { this.mutationCache.onFocus() this.queryCache.onFocus() } }) this.unsubscribeOnline = onlineManager.subscribe(() => { if (focusManager.isFocused() && onlineManager.isOnline()) { this.mutationCache.onOnline() this.queryCache.onOnline() } }) } unmount(): void { this.unsubscribeFocus?.() this.unsubscribeOnline?.() } isFetching(filters?: QueryFilters): number isFetching(queryKey?: QueryKey, filters?: QueryFilters): number isFetching(arg1?: QueryKey | QueryFilters, arg2?: QueryFilters): number { const [filters] = parseFilterArgs(arg1, arg2) filters.fetching = true return this.queryCache.findAll(filters).length } isMutating(filters?: MutationFilters): number { return this.mutationCache.findAll({ ...filters, fetching: true }).length } getQueryData<TData = unknown>( queryKey: QueryKey, filters?: QueryFilters ): TData | undefined { return this.queryCache.find<TData>(queryKey, filters)?.state.data } getQueriesData<TData = unknown>(queryKey: QueryKey): [QueryKey, TData][] getQueriesData<TData = unknown>(filters: QueryFilters): [QueryKey, TData][] getQueriesData<TData = unknown>( queryKeyOrFilters: QueryKey | QueryFilters ): [QueryKey, TData][] { return this.getQueryCache() .findAll(queryKeyOrFilters) .map(({ queryKey, state }) => { const data = state.data as TData return [queryKey, data] }) } setQueryData<TData>( queryKey: QueryKey, updater: Updater<TData | undefined, TData>, options?: SetDataOptions ): TData { const parsedOptions = parseQueryArgs(queryKey) const defaultedOptions = this.defaultQueryOptions(parsedOptions) return this.queryCache .build(this, defaultedOptions) .setData(updater, options) } setQueriesData<TData>( queryKey: QueryKey, updater: Updater<TData | undefined, TData>, options?: SetDataOptions ): [QueryKey, TData][] setQueriesData<TData>( filters: QueryFilters, updater: Updater<TData | undefined, TData>, options?: SetDataOptions ): [QueryKey, TData][] setQueriesData<TData>( queryKeyOrFilters: QueryKey | QueryFilters, updater: Updater<TData | undefined, TData>, options?: SetDataOptions ): [QueryKey, TData][] { return notifyManager.batch(() => this.getQueryCache() .findAll(queryKeyOrFilters) .map(({ queryKey }) => [ queryKey, this.setQueryData<TData>(queryKey, updater, options), ]) ) } getQueryState<TData = unknown, TError = undefined>( queryKey: QueryKey, filters?: QueryFilters ): QueryState<TData, TError> | undefined { return this.queryCache.find<TData, TError>(queryKey, filters)?.state } removeQueries(filters?: QueryFilters): void removeQueries(queryKey?: QueryKey, filters?: QueryFilters): void removeQueries(arg1?: QueryKey | QueryFilters, arg2?: QueryFilters): void { const [filters] = parseFilterArgs(arg1, arg2) const queryCache = this.queryCache notifyManager.batch(() => { queryCache.findAll(filters).forEach(query => { queryCache.remove(query) }) }) } resetQueries<TPageData = unknown>( filters?: ResetQueryFilters<TPageData>, options?: ResetOptions ): Promise<void> resetQueries<TPageData = unknown>( queryKey?: QueryKey, filters?: ResetQueryFilters<TPageData>, options?: ResetOptions ): Promise<void> resetQueries( arg1?: QueryKey | ResetQueryFilters, arg2?: ResetQueryFilters | ResetOptions, arg3?: ResetOptions ): Promise<void> { const [filters, options] = parseFilterArgs(arg1, arg2, arg3) const queryCache = this.queryCache const refetchFilters: RefetchQueryFilters = { ...filters, active: true, } return notifyManager.batch(() => { queryCache.findAll(filters).forEach(query => { query.reset() }) return this.refetchQueries(refetchFilters, options) }) } cancelQueries(filters?: QueryFilters, options?: CancelOptions): Promise<void> cancelQueries( queryKey?: QueryKey, filters?: QueryFilters, options?: CancelOptions ): Promise<void> cancelQueries( arg1?: QueryKey | QueryFilters, arg2?: QueryFilters | CancelOptions, arg3?: CancelOptions ): Promise<void> { const [filters, cancelOptions = {}] = parseFilterArgs(arg1, arg2, arg3) if (typeof cancelOptions.revert === 'undefined') { cancelOptions.revert = true } const promises = notifyManager.batch(() => this.queryCache.findAll(filters).map(query => query.cancel(cancelOptions)) ) return Promise.all(promises).then(noop).catch(noop) } invalidateQueries<TPageData = unknown>( filters?: InvalidateQueryFilters<TPageData>, options?: InvalidateOptions ): Promise<void> invalidateQueries<TPageData = unknown>( queryKey?: QueryKey, filters?: InvalidateQueryFilters<TPageData>, options?: InvalidateOptions ): Promise<void> invalidateQueries( arg1?: QueryKey | InvalidateQueryFilters, arg2?: InvalidateQueryFilters | InvalidateOptions, arg3?: InvalidateOptions ): Promise<void> { const [filters, options] = parseFilterArgs(arg1, arg2, arg3) const refetchFilters: RefetchQueryFilters = { ...filters, // if filters.refetchActive is not provided and filters.active is explicitly false, // e.g. invalidateQueries({ active: false }), we don't want to refetch active queries active: filters.refetchActive ?? filters.active ?? true, inactive: filters.refetchInactive ?? false, } return notifyManager.batch(() => { this.queryCache.findAll(filters).forEach(query => { query.invalidate() }) return this.refetchQueries(refetchFilters, options) }) } refetchQueries<TPageData = unknown>( filters?: RefetchQueryFilters<TPageData>, options?: RefetchOptions ): Promise<void> refetchQueries<TPageData = unknown>( queryKey?: QueryKey, filters?: RefetchQueryFilters<TPageData>, options?: RefetchOptions ): Promise<void> refetchQueries( arg1?: QueryKey | RefetchQueryFilters, arg2?: RefetchQueryFilters | RefetchOptions, arg3?: RefetchOptions ): Promise<void> { const [filters, options] = parseFilterArgs(arg1, arg2, arg3) const promises = notifyManager.batch(() => this.queryCache.findAll(filters).map(query => query.fetch(undefined, { ...options, meta: { refetchPage: filters?.refetchPage }, }) ) ) let promise = Promise.all(promises).then(noop) if (!options?.throwOnError) { promise = promise.catch(noop) } return promise } fetchQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( options: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<TData> fetchQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( queryKey: TQueryKey, options?: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<TData> fetchQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( queryKey: TQueryKey, queryFn: QueryFunction<TQueryFnData, TQueryKey>, options?: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<TData> fetchQuery< TQueryFnData, TError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( arg1: TQueryKey | FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, arg2?: | QueryFunction<TQueryFnData, TQueryKey> | FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, arg3?: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<TData> { const parsedOptions = parseQueryArgs(arg1, arg2, arg3) const defaultedOptions = this.defaultQueryOptions(parsedOptions) // https://github.com/tannerlinsley/react-query/issues/652 if (typeof defaultedOptions.retry === 'undefined') { defaultedOptions.retry = false } const query = this.queryCache.build(this, defaultedOptions) return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data as TData) } prefetchQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( options: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<void> prefetchQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( queryKey: TQueryKey, options?: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<void> prefetchQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( queryKey: TQueryKey, queryFn: QueryFunction<TQueryFnData, TQueryKey>, options?: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<void> prefetchQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( arg1: TQueryKey | FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, arg2?: | QueryFunction<TQueryFnData, TQueryKey> | FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, arg3?: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<void> { return this.fetchQuery(arg1 as any, arg2 as any, arg3) .then(noop) .catch(noop) } fetchInfiniteQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( options: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<InfiniteData<TData>> fetchInfiniteQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( queryKey: TQueryKey, options?: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<InfiniteData<TData>> fetchInfiniteQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( queryKey: TQueryKey, queryFn: QueryFunction<TQueryFnData, TQueryKey>, options?: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<InfiniteData<TData>> fetchInfiniteQuery< TQueryFnData, TError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( arg1: | TQueryKey | FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>, arg2?: | QueryFunction<TQueryFnData, TQueryKey> | FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>, arg3?: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<InfiniteData<TData>> { const parsedOptions = parseQueryArgs(arg1, arg2, arg3) parsedOptions.behavior = infiniteQueryBehavior< TQueryFnData, TError, TData >() return this.fetchQuery(parsedOptions) } prefetchInfiniteQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( options: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<void> prefetchInfiniteQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( queryKey: TQueryKey, options?: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<void> prefetchInfiniteQuery< TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( queryKey: TQueryKey, queryFn: QueryFunction<TQueryFnData, TQueryKey>, options?: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<void> prefetchInfiniteQuery< TQueryFnData, TError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey >( arg1: | TQueryKey | FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>, arg2?: | QueryFunction<TQueryFnData, TQueryKey> | FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>, arg3?: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey> ): Promise<void> { return this.fetchInfiniteQuery(arg1 as any, arg2 as any, arg3) .then(noop) .catch(noop) } cancelMutations(): Promise<void> { const promises = notifyManager.batch(() => this.mutationCache.getAll().map(mutation => mutation.cancel()) ) return Promise.all(promises).then(noop).catch(noop) } resumePausedMutations(): Promise<void> { return this.getMutationCache().resumePausedMutations() } executeMutation< TData = unknown, TError = unknown, TVariables = void, TContext = unknown >( options: MutationOptions<TData, TError, TVariables, TContext> ): Promise<TData> { return this.mutationCache.build(this, options).execute() } getQueryCache(): QueryCache { return this.queryCache } getMutationCache(): MutationCache { return this.mutationCache } getDefaultOptions(): DefaultOptions { return this.defaultOptions } setDefaultOptions(options: DefaultOptions): void { this.defaultOptions = options } setQueryDefaults( queryKey: QueryKey, options: QueryObserverOptions<any, any, any, any> ): void { const result = this.queryDefaults.find( x => hashQueryKey(queryKey) === hashQueryKey(x.queryKey) ) if (result) { result.defaultOptions = options } else { this.queryDefaults.push({ queryKey, defaultOptions: options }) } } getQueryDefaults( queryKey?: QueryKey ): QueryObserverOptions<any, any, any, any, any> | undefined { return queryKey ? this.queryDefaults.find(x => partialMatchKey(queryKey, x.queryKey)) ?.defaultOptions : undefined } setMutationDefaults( mutationKey: MutationKey, options: MutationObserverOptions<any, any, any, any> ): void { const result = this.mutationDefaults.find( x => hashQueryKey(mutationKey) === hashQueryKey(x.mutationKey) ) if (result) { result.defaultOptions = options } else { this.mutationDefaults.push({ mutationKey, defaultOptions: options }) } } getMutationDefaults( mutationKey?: MutationKey ): MutationObserverOptions<any, any, any, any> | undefined { return mutationKey ? this.mutationDefaults.find(x => partialMatchKey(mutationKey, x.mutationKey) )?.defaultOptions : undefined } defaultQueryOptions< TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey >( options?: QueryObserverOptions< TQueryFnData, TError, TData, TQueryData, TQueryKey > ): QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey> { if (options?._defaulted) { return options } const defaultedOptions = { ...this.defaultOptions.queries, ...this.getQueryDefaults(options?.queryKey), ...options, _defaulted: true, } as QueryObserverOptions< TQueryFnData, TError, TData, TQueryData, TQueryKey > if (!defaultedOptions.queryHash && defaultedOptions.queryKey) { defaultedOptions.queryHash = hashQueryKeyByOptions( defaultedOptions.queryKey, defaultedOptions ) } return defaultedOptions } defaultQueryObserverOptions< TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey >( options?: QueryObserverOptions< TQueryFnData, TError, TData, TQueryData, TQueryKey > ): QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey> { return this.defaultQueryOptions(options) } defaultMutationOptions<T extends MutationOptions<any, any, any, any>>( options?: T ): T { if (options?._defaulted) { return options } return { ...this.defaultOptions.mutations, ...this.getMutationDefaults(options?.mutationKey), ...options, _defaulted: true, } as T } clear(): void { this.queryCache.clear() this.mutationCache.clear() } }
the_stack
import { onnx } from "onnx-proto"; import { Backend, DataType, backendsWithoutCPU, backends, } from "../interface/core/constants"; import { clipLong, intOrLongToInt, intOrLongToIntVector, nonnull, } from "../util"; import Long from "long"; import { InputProxy } from "./inputProxy"; import { OutputProxy } from "./outputProxy"; import { findTensorReleaseTiming, modelTransform } from "./modelTransform"; import { CPUTensor } from "../interface/backend/cpu/cpuTensor"; import { Tensor } from "../interface/core/tensor"; import { WebGPUTensor } from "../interface/backend/webgpu/webgpuTensor"; import { WebGLTensor } from "../interface/backend/webgl/webglTensor"; import { WasmTensor } from "../interface/backend/wasm/wasmTensor"; import { instantiateOperator } from "./operatorTable"; import { Runner } from "../interface/core/runner"; import { WebDNNCPUContext } from "../interface/backend/cpu/cpuContext"; import { WebDNNWasmContext } from "../interface/backend/wasm/wasmContext"; import { WebDNNWebGLContext } from "../interface/backend/webgl/webglContext"; import { WebDNNWebGPUContext } from "../interface/backend/webgpu/webgpuContext"; import { TensorLoaderImpl } from "./tensorLoaderImpl"; import { TensorLoader } from "../interface/core/tensorLoader"; import { WebDNNLogging } from "../logging"; const logger = WebDNNLogging.getLogger("WebDNN.runner"); export interface BackendContexts { cpu: WebDNNCPUContext; wasm?: WebDNNWasmContext; webgl?: WebDNNWebGLContext; webgpu?: WebDNNWebGPUContext; } export class RunnerImpl implements Runner { model?: onnx.ModelProto; loaded: boolean; initializerTensors!: Map<string, CPUTensor>; copiedInitializerTensors!: Map<Backend, Map<string, Tensor>>; useCompatibilityProxy: boolean; inputs!: InputProxy[]; outputs!: OutputProxy[]; opset!: number; tensorMoveOptions: { [key: string]: Record<string, any> }; /** * key: operator name */ forceOperatorBackendOrder: { [key: string]: Backend[] }; /** * Primary backend */ readonly backendName: Backend; constructor( public backendOrder: Backend[], private backendContexts: BackendContexts ) { this.backendName = this.backendOrder[0]; this.loaded = false; this.useCompatibilityProxy = false; this.tensorMoveOptions = {}; this.forceOperatorBackendOrder = {}; } getTensorLoader(path: string[] | string): TensorLoader { return new TensorLoaderImpl(path, this.backendContexts.cpu); } async loadModel(directory: string, onnxBasename: string): Promise<void> { const f = await fetch(directory + onnxBasename), b = await f.arrayBuffer(); this.model = onnx.ModelProto.decode(new Uint8Array(b)); modelTransform(this.model, this.backendOrder); if (this.model!.opsetImport.length !== 1) { logger.warn( `Specifying multiple opset_import is not supported. Using first one.` ); } this.opset = intOrLongToInt(this.model!.opsetImport[0].version!); this.initializerTensors = new Map(); for (const [name, tensor] of this.extractInitializerTensor().entries()) { this.initializerTensors.set(name, tensor); } for (const [name, tensor] of ( await this.loadExternalInitializerTensor(directory) ).entries()) { this.initializerTensors.set(name, tensor); } if (this.useCompatibilityProxy) { this.initInputProxy(); this.initOutputProxy(); } this.copiedInitializerTensors = new Map(); for (const backend of this.backendOrder) { if (backend !== "cpu") { this.copiedInitializerTensors.set(backend, new Map()); } } for (const md of this.model!.metadataProps) { if (md.key === "WebDNN2.TensorMoveOptions") { this.tensorMoveOptions = JSON.parse(md.value!); } if (md.key === "WebDNN2.ForceOperatorBackendOrder") { this.forceOperatorBackendOrder = JSON.parse(md.value!); } } this.loaded = true; } private extractInitializerTensor(): Map<string, CPUTensor> { const tensors = new Map<string, CPUTensor>(); for (const initializer of this.model!.graph!.initializer!) { const dims = intOrLongToIntVector(initializer.dims!); if (initializer.dataType === onnx.TensorProto.DataType.FLOAT) { if (initializer.rawData?.byteLength) { // Float32Array(initializer.rawData!.buffer) は不可(4byteにアライメントされていない場合がある) const newBuffer = new Uint8Array(initializer.rawData!.byteLength); newBuffer.set(initializer.rawData!); tensors.set( initializer.name!, this.backendContexts.cpu.emptyTensor( dims, "float32", new Float32Array( newBuffer.buffer, 0, newBuffer.byteLength / Float32Array.BYTES_PER_ELEMENT ) ) ); } else if (initializer.floatData) { tensors.set( initializer.name!, this.backendContexts.cpu.emptyTensor( dims, "float32", new Float32Array(initializer.floatData) ) ); } } else if (initializer.dataType === onnx.TensorProto.DataType.INT64) { // 1要素が8byte (int64) if (initializer.rawData?.byteLength) { const rawData = initializer.rawData!, view = new DataView( rawData.buffer, rawData.byteOffset, rawData.byteLength ), ab = new Int32Array(view.byteLength / 8); for (let idx = 0; idx < ab.length; idx++) { ab[idx] = clipLong( new Long( view.getUint32(idx * 8, true), view.getUint32(idx * 8 + 4, true) ) ); } tensors.set( initializer.name!, this.backendContexts.cpu.emptyTensor(dims, "int32", ab) ); } else if (initializer.int64Data) { tensors.set( initializer.name!, this.backendContexts.cpu.emptyTensor( dims, "int32", new Int32Array(intOrLongToIntVector(initializer.int64Data)) ) ); } } else if (initializer.dataType === onnx.TensorProto.DataType.INT32) { if (initializer.rawData?.byteLength) { // 1要素が4byte (int32) const rawData = initializer.rawData!, view = new DataView( rawData.buffer, rawData.byteOffset, rawData.byteLength ), ab = new Int32Array(view.byteLength / 4); for (let idx = 0; idx < ab.length; idx++) { ab[idx] = view.getInt32(idx * 4, true); } tensors.set( initializer.name!, this.backendContexts.cpu.emptyTensor(dims, "int32", ab) ); } else if (initializer.int32Data) { tensors.set( initializer.name!, this.backendContexts.cpu.emptyTensor( dims, "int32", new Int32Array(initializer.int32Data) ) ); } } else { throw new Error( `Unsupported initializer dataType ${initializer.dataType}` ); } } return tensors; } private async loadExternalInitializerTensor( directory: string ): Promise<Map<string, CPUTensor>> { for (const md of this.model!.metadataProps) { if (md.key === "WebDNN2.WeightPaths") { const paths = md.value!.split(":").map((bn) => directory + bn), loader = this.getTensorLoader(paths); return loader.loadAll(); } } return new Map(); } private getIOProxyShape(vi: onnx.IValueInfoProto) { const shape = nonnull( vi.type?.tensorType?.shape?.dim?.map((d) => intOrLongToInt(nonnull(d.dimValue)) ) ); let dataType: DataType; switch (vi.type?.tensorType?.elemType) { case onnx.TensorProto.DataType.FLOAT: dataType = "float32"; break; case onnx.TensorProto.DataType.INT32: case onnx.TensorProto.DataType.INT64: dataType = "int32"; break; default: throw new Error(); } return { shape, dataType }; } private initInputProxy() { const graph = nonnull(this.model?.graph); this.inputs = graph.input!.map((input) => { const { shape, dataType } = this.getIOProxyShape(input); return new InputProxy(shape, dataType); }); } private initOutputProxy() { const graph = nonnull(this.model?.graph); this.outputs = graph.output!.map((input) => { const { shape, dataType } = this.getIOProxyShape(input); return new OutputProxy(shape, dataType); }); } getInputNames(): string[] { const graph = nonnull(this.model?.graph); return graph.input!.map((gi) => gi.name!); } getOutputNames(): string[] { const graph = nonnull(this.model?.graph); return graph.output!.map((gi) => gi.name!); } async run(inputs?: CPUTensor[]): Promise<CPUTensor[]> { if (!this.model || !this.loaded) { throw new Error("not initialized"); } const graph = nonnull(this.model.graph), tensorsForBackends = { cpu: new Map<string, CPUTensor>(), wasm: new Map<string, WasmTensor>(), webgl: new Map<string, WebGLTensor>(), webgpu: new Map<string, WebGPUTensor>(), }; for (const [name, tensor] of this.initializerTensors.entries()) { tensorsForBackends.cpu.set(name, tensor); } for (const [backend, kv] of this.copiedInitializerTensors.entries()) { for (const [name, tensor] of kv.entries()) { tensorsForBackends[backend].set(name, tensor as any); } } if (!inputs) { // From inputProxy if (this.useCompatibilityProxy) { inputs = this.inputs.map((v) => { const t = this.backendContexts.cpu.emptyTensor(v.dims, v.dataType); t.data.set(v); return t; }); } else { throw new Error(); } } // 入力設定 if (graph.input!.length !== inputs.length) { throw new Error("length of inputs mismatch"); } for (let i = 0; i < inputs.length; i++) { const graphInput = graph.input![i]; // if (graphInput.type!.tensorType!.elemType !== 1) { // throw new Error("graph input type must be float32"); // } tensorsForBackends.cpu.set(graphInput.name!, inputs[i]); } const tensorReleaseTiming = findTensorReleaseTiming( this.model!, new Set(this.initializerTensors.keys()) ), nodePerformances: { opType: string; name: string; backend: Backend; inputDims: ReadonlyArray<number>[]; outputDims: ReadonlyArray<number>[]; elapsed: number; }[] = []; for (let i = 0; i < graph.node!.length; i++) { const nodeStartTime = Date.now(), node = graph.node![i], opType = nonnull(node.opType); let actualBackend: Backend, actualInputDims: ReadonlyArray<number>[], actualOutputDims: ReadonlyArray<number>[], backendOrderForNode = this.forceOperatorBackendOrder[node.name!] || this.backendOrder; let firstTry = true; // eslint-disable-next-line no-constant-condition while (true) { try { // テンソルがどこにあるのか調べる const currentTensorsBackends: Backend[][] = []; for (let j = 0; j < node.input!.length; j++) { const inputName = node.input![j], bs: Backend[] = []; for (const backend of backendOrderForNode) { if (tensorsForBackends[backend].has(inputName)) { bs.push(backend); } } if (bs.length === 0) { // forceOperatorBackendOrder == ["webgl"]のような場合に、cpu上にあるTensorをスキャンする for (const backend of backends) { if (tensorsForBackends[backend].has(inputName)) { bs.push(backend); } } } currentTensorsBackends.push(bs); } const operator = instantiateOperator( opType, this.opset, backendOrderForNode, currentTensorsBackends ); if (!operator) { throw new Error( `Operator implementation for ${opType}, opset=${this.opset} does not exist.` ); } operator.initialize(nonnull(node.attribute)); const tensorBackendRequirement = operator.getTensorBackendRequirement( node.input!.length, node.output!.length ), // 入力を集める operatorInputs: Tensor[] = []; for (let j = 0; j < node.input!.length; j++) { const inputName = node.input![j], reqBackend = tensorBackendRequirement[j]; if (!reqBackend) { // どこでもいい const t = tensorsForBackends[currentTensorsBackends[j][0]].get(inputName); if (!t) { throw new Error(); } operatorInputs.push(t); } else { const t = tensorsForBackends[reqBackend].get(inputName); if (t) { operatorInputs.push(t); } else { let found = false; for (const otherBackend of this.backendOrder) { const otherT = tensorsForBackends[otherBackend].get(inputName); if (otherT) { const tensorMoveOption = this.tensorMoveOptions[inputName] || {}, movedT = await this.backendContexts[ reqBackend ]!.moveTensor(otherT, tensorMoveOption); tensorsForBackends[reqBackend].set( inputName, movedT as any ); operatorInputs.push(movedT); found = true; break; } } if (!found) { throw new Error(`Input ${inputName} not found`); } } } } let context: any = {}; switch (operator.backend) { case "wasm": context = this.backendContexts.wasm; break; case "webgpu": context = this.backendContexts.webgpu; break; case "webgl": context = this.backendContexts.webgl; break; case "cpu": context = this.backendContexts.cpu; break; default: throw new Error(); } logger.debug( `Running ${node.name!}(${opType}) on ${operator.backend}` ); const operatorOutputs = await operator.run( context, operatorInputs, node.output!.length ); actualInputDims = operatorInputs.map((t) => t.dims); actualOutputDims = operatorOutputs.map((t) => t.dims); for (let j = 0; j < node.output!.length; j++) { const outputName = node.output![j]; tensorsForBackends[operatorOutputs[j].backend].set( outputName, operatorOutputs[j] as any ); } actualBackend = operator.backend; break; } catch (error) { if (firstTry) { logger.warn(`Failed to run ${node.name}. Retrying on cpu.`, error); firstTry = false; backendOrderForNode = ["cpu"]; continue; } else { throw error; } } } const tensorNamesToRelease = tensorReleaseTiming.get(node.name!) || []; for (const name of tensorNamesToRelease) { for (const backend of Object.keys(tensorsForBackends) as Backend[]) { const t = tensorsForBackends[backend].get(name); if (t) { t.dispose(); tensorsForBackends[backend].delete(name); } } } const nodeEndTime = Date.now(); nodePerformances.push({ opType: node.opType!, name: node.name!, backend: actualBackend, inputDims: actualInputDims, outputDims: actualOutputDims, elapsed: nodeEndTime - nodeStartTime, }); } const outputs = []; for (let j = 0; j < graph.output!.length; j++) { const outputInfo = graph.output![j]; let outputTensor = tensorsForBackends.cpu.get(outputInfo.name!); if (!outputTensor) { for (const otherBackend of this.backendOrder) { const otherT = tensorsForBackends[otherBackend].get(outputInfo.name!); if (otherT) { const movedT = await this.backendContexts.cpu.moveTensor( otherT, {} ); tensorsForBackends.cpu.set(outputInfo.name!, movedT as any); outputTensor = movedT; break; } } } if (!outputTensor) { throw new Error(`Output ${outputInfo.name} not found`); } if (this.useCompatibilityProxy) { // Copy value to output proxy this.outputs[j].set(outputTensor.data); } outputs.push(outputTensor); } for (const backend of backendsWithoutCPU) { for (const [name, t] of tensorsForBackends[backend].entries()) { if (this.initializerTensors.has(name)) { this.copiedInitializerTensors.get(backend)!.set(name, t); } else { t.dispose(); } } } logger.debug("Performance", nodePerformances); return outputs; } }
the_stack
import { groupBy, size } from '@antv/util'; import { Facet } from '../../../../src'; import { createDiv } from '../../../utils/dom'; import { delay } from '../../../utils/delay'; import { simulateMouseEvent } from '../../../utils/event'; describe('facet', () => { const data = [ { type: '1', date: '2014-01', value: 1, name: 'a' }, { type: '1', date: '2015-01', value: 1, name: 'b' }, { type: '1', date: '2016-01', value: 1, name: 'c' }, { type: '1', date: '2017-01', value: 1, name: 'd' }, { type: '2', date: '2014-01', value: 1, name: 'a' }, { type: '2', date: '2015-01', value: 1, name: 'b' }, { type: '2', date: '2016-01', value: 1, name: 'a' }, { type: '2', date: '2017-01', value: 1, name: 'd' }, { type: '3', date: '2014-01', value: 1, name: 'b' }, { type: '4', date: '2015-01', value: 1, name: 'd' }, { type: '4', date: '2016-01', value: 10, name: 'b' }, { type: '4', date: '2017-01', value: 1, name: 'c' }, ]; const plot = new Facet(createDiv(), { data, type: 'rect', fields: ['type'], eachView: () => { return { geometries: [{ type: 'interval', xField: 'date', yField: 'value', colorField: 'name', mapping: {} }] }; }, theme: { colors10: ['red', 'green', 'yellow', 'blue'], }, showTitle: false, meta: { date: { sync: true } }, }); plot.render(); it('default', () => { expect(plot.chart.views.length).toBe(size(groupBy(data, 'type'))); const [view0, view1, view2, view3] = plot.chart.views; // 同步 facet 顶层设置的主题 expect(view0.geometries[0].getAttribute('color').values).toEqual(['red', 'green', 'yellow', 'blue']); expect(view1.geometries[0].getAttribute('color').values).toEqual(['red', 'green', 'yellow', 'blue']); expect(view2.geometries[0].getAttribute('color').values).toEqual(['red', 'green', 'yellow', 'blue']); expect(view3.geometries[0].elements[0].getModel().color).toBe('red'); expect(view0.geometries[0].elements[0].getModel().color).toBe(view3.geometries[0].elements[0].getModel().color); }); it('sync colorField, make colorField mapping between facets', () => { plot.update({ meta: { name: { sync: true } } }); const [view0, view1, view2, view3] = plot.chart.views; expect(view0.geometries[0].elements[0].getModel().color).toBe('red'); expect(view1.geometries[0].elements[0].getModel().color).toBe('red'); expect(view2.geometries[0].elements[0].getModel().color).toBe('green'); expect(view3.geometries[0].elements[0].getModel().color).toBe('blue'); }); it('meta, 支持顶层配置和单独配置', () => { plot.update({ meta: { name: { sync: true, values: ['d', 'c', 'b', 'a'] } }, }); const [view0, , view2, view3] = plot.chart.views; expect(view0.geometries[0].elements[0].getModel().color).toBe('red'); const data0 = view0.geometries[0].elements[0].getModel().data as any; const data1 = view0.geometries[0].elements[1].getModel().data as any; const data2 = view0.geometries[0].elements[2].getModel().data as any; const data3 = view0.geometries[0].elements[3].getModel().data as any; expect(data0.name).toBe('d'); expect(data1.name).toBe('c'); expect(data2.name).toBe('b'); expect(data3.name).toBe('a'); expect(view2.geometries[0].elements[0].getModel().color).toBe('yellow'); expect(view3.geometries[0].elements[0].getModel().color).toBe('red'); const view1data0 = plot.chart.views[1].geometries[0].elements[0].getModel().data as any; const view3data0 = plot.chart.views[3].geometries[0].elements[0].getModel().data as any; expect(view1data0.name).toBe(view3data0.name); plot.update({ eachView: (view, facet) => { const { columnIndex } = facet; return { meta: { name: columnIndex === 3 ? { sync: false } : {} }, geometries: [ { type: 'interval', xField: 'date', yField: 'value', colorField: 'name', mapping: {}, }, ], }; }, }); expect(plot.chart.views[1].geometries[0].elements[0].getModel().color).toBe('blue'); const view1data = plot.chart.views[1].geometries[0].elements[0].getModel().data as any; const view3data = plot.chart.views[3].geometries[0].elements[0].getModel().data as any; // 设置 scale 不同步之后,第一条数据就相等了 expect(view1data.name).not.toBe(view3data.name); }); it('axes, 支持顶层配置和单独配置 (顶层配置优先级 < 单独设置)', () => { expect(plot.chart.views[0].getController('axis').getComponents().length).toBe(0); plot.update({ axes: {} }); expect(plot.chart.views[0].getController('axis').getComponents().length).not.toBe(0); plot.update({ eachView: (view, facet) => { const { columnIndex } = facet; return { geometries: [{ type: 'interval', xField: 'date', yField: 'value', colorField: 'name', mapping: {} }], axes: { date: columnIndex === 0 ? false : {}, value: columnIndex === 0 ? false : {} }, }; }, }); expect(plot.chart.views[0].getController('axis').getComponents().length).toBe(0); expect(plot.chart.views[1].getController('axis').getComponents().length).not.toBe(0); }); it('tooltip, 支持顶层配置和单独配置 (顶层配置优先级 < 单独设置)', () => { expect(plot.chart.views[0].getController('tooltip')).toBeDefined(); expect(plot.chart.interactions['tooltip']).not.toBeUndefined(); plot.update({ tooltip: false }); expect(plot.chart.interactions['tooltip']).toBeUndefined(); plot.update({ tooltip: {} }); expect(plot.chart.interactions['tooltip']).not.toBeUndefined(); plot.update({ eachView: (view, facet) => { const { columnIndex } = facet; return { geometries: [{ type: 'interval', xField: 'date', yField: 'value', colorField: 'name', mapping: {} }], tooltip: columnIndex === 0 ? false : {}, }; }, }); expect(plot.chart.views[0].interactions['tooltip']).toBeUndefined(); expect(plot.chart.views[1].interactions['tooltip']).not.toBeUndefined(); }); it('interaction, 支持顶层配置和单独配置 (💡 顶层配置优先级 > 单独设置)', () => { plot.update({ interactions: [{ type: 'tooltip', enable: false }] }); expect(plot.chart.interactions['tooltip']).toBeUndefined(); plot.update({ interactions: [{ type: 'element-active' }] }); expect(plot.chart.interactions['element-active']).toBeDefined(); expect(plot.chart.views[0].interactions['element-active']).not.toBeDefined(); expect(plot.chart.views[1].interactions['element-active']).not.toBeDefined(); const element = plot.chart.views[0].geometries[0].elements[0]; const element10 = plot.chart.views[1].geometries[0].elements[0]; let element1 = plot.chart.views[0].geometries[0].elements[1]; simulateMouseEvent(element.shape, 'mouseenter'); simulateMouseEvent(element10.shape, 'mouseenter'); expect(element.shape.attr('stroke')).toBe('#000'); expect(element10.shape.attr('stroke')).toBe('#000'); expect(element1.shape.attr('stroke')).not.toBe('#000'); plot.update({ eachView: () => { return { geometries: [{ type: 'interval', xField: 'date', yField: 'value', colorField: 'name', mapping: {} }], interactions: [{ type: 'element-active', enable: false }], }; }, }); element1 = plot.chart.views[0].geometries[0].elements[1]; simulateMouseEvent(element1.shape, 'mouseenter'); expect(element1.shape.attr('stroke')).toBe('#000'); plot.update({ interactions: [{ type: 'element-active', enable: false }] }); element1 = plot.chart.views[0].geometries[0].elements[1]; simulateMouseEvent(element1.shape, 'mouseenter'); expect(element1.shape.attr('stroke')).not.toBe('#000'); // views[0] 设置 element-active 交互 plot.update({ eachView: (view, facet) => { return { geometries: [{ type: 'interval', xField: 'date', yField: 'value', colorField: 'name', mapping: {} }], interactions: facet.columnIndex === 0 ? [{ type: 'element-active' }] : [], }; }, }); const view1Element = plot.chart.views[0].geometries[0].elements[0]; const view2Element = plot.chart.views[1].geometries[0].elements[0]; simulateMouseEvent(view1Element.shape, 'mouseenter'); simulateMouseEvent(view2Element.shape, 'mouseenter'); expect(view1Element.shape.attr('stroke')).toBe('#000'); expect(view2Element.shape.attr('stroke')).not.toBe('#000'); }); it('animation, 支持单独配置 & 暂不支持顶层配置', () => { plot.update({ eachView: (view, facet) => { return { geometries: [{ type: 'interval', xField: 'date', yField: 'value', colorField: 'name', mapping: {} }], animation: facet.columnIndex === 0 ? {} : false, }; }, }); // @ts-ignore expect(plot.chart.views[0].options.animate).toBe(true); // @ts-ignore expect(plot.chart.views[1].options.animate).toBe(false); }); it('label, 支持单独配置 & 不支持顶层配置', async () => { plot.update({ eachView: (view, facet) => { return { geometries: [ { type: 'interval', xField: 'date', yField: 'value', colorField: 'name', mapping: {}, label: facet.columnIndex === 0 ? {} : false, }, ], }; }, }); await delay(0); expect(plot.chart.views[0].geometries[0].labelsContainer.getChildren().length).toBeGreaterThan(0); expect(plot.chart.views[1].geometries[0].labelsContainer.getChildren().length).toBe(0); }); it('annotations, 支持顶层配置和单独配置', () => { expect(plot.chart.getController('annotation').getComponents().length).toBe(0); expect(plot.chart.views[0].getController('annotation').getComponents().length).toBe(0); const annotation: any = { type: 'text', position: ['50%', '50%'], content: 'xx' }; plot.update({ annotations: [annotation] }); expect(plot.chart.getController('annotation').getComponents().length).toBe(1); plot.update({ eachView: (view, facet) => { return { geometries: [{ type: 'interval', xField: 'date', yField: 'value', colorField: 'name', mapping: {} }], annotations: facet.columnIndex === 0 ? [annotation, annotation] : [annotation], }; }, }); expect(plot.chart.views[0].getController('annotation').getComponents().length).toBe(2); expect(plot.chart.views[1].getController('annotation').getComponents().length).toBe(1); plot.update({ annotations: [] }); expect(plot.chart.views[0].getController('annotation').getComponents().length).toBe(2); expect(plot.chart.views[1].getController('annotation').getComponents().length).toBe(1); expect(plot.chart.getController('annotation').getComponents().length).toBe(0); plot.update({ showTitle: true }); // facet title 也是一个 annotation expect(plot.chart.views[0].getController('annotation').getComponents().length).toBe(3); expect(plot.chart.views[1].getController('annotation').getComponents().length).toBe(2); }); it('legend, 顶层设置', () => { // @ts-ignore expect(plot.chart.getController('legend').getComponents()[0].component.getItems().length).toBe( size(groupBy(data, 'name')) ); plot.update({ legend: false }); expect(plot.chart.getController('legend').getComponents().length).toBe(0); }); it('theme, 暂时只支持顶层设置', () => { plot.update({ theme: 'dark' }); expect(plot.chart.getTheme().background).toBe('#141414'); }); afterAll(() => { plot.destroy(); }); });
the_stack
import { RegisterItem } from "../core/Register"; import { DownMotion } from "../motion/DownMotion"; import { LastCharacterInLineMotion } from "../motion/LastCharacterInLineMotion"; import { RightMotion } from "../motion/RightMotion"; import { Position, Range } from "../VimStyle"; import { AbstractInsertTextAction } from "./AbstractInsertTextAction"; /** * dm ym cm D Y M * x X s S */ export class DeleteYankChangeAction extends AbstractInsertTextAction implements IRequireMotionAction, IInsertTextAction { public Motion: IMotion; public Selection: ISelectionMotion; public IsLine: boolean; public IsLarge: boolean; public IsChange: boolean; public IsOnlyYanc: boolean; constructor() { super(); this.Motion = null; this.IsLine = false; this.IsLarge = true; this.IsChange = false; this.IsOnlyYanc = false; } public GetActionType(): ActionType { if (this.IsOnlyYanc) { return ActionType.Other; } else if (this.IsChange) { return ActionType.Insert; } return ActionType.Edit; } public Execute(editor: IEditor, vim: IVimStyle) { let range = new Range(); range.start = editor.GetCurrentPosition(); if (this.Motion) { let p = this.Motion.CalculateEnd(editor, vim, range.start); if (p == null) { // cancel return; } range.end = p; range.Sort(); } else if (this.Selection) { range = this.Selection.CalculateRange(editor, vim, range.start); if (range == null) { // cancel return; } } if (this.IsLine) { this.deleteLine(range, editor, vim); } else { this.deleteRange(range, editor, vim); } } private deleteRange(range: Range, editor: IEditor, vim: IVimStyle) { let nextPosition = new Position(); nextPosition.Line = range.start.Line; let endLine = editor.ReadLine(range.end.Line); if (range.start.Char === 0) { // delete from home of line nextPosition.Char = 0; } else { if (endLine.length <= range.end.Char) { // delete to end of line if (this.IsChange) { nextPosition.Char = range.start.Char; } else { nextPosition.Char = range.start.Char - 1; } } else { // delete immidiate nextPosition.Char = range.start.Char; } } let item = new RegisterItem(); item.Body = editor.ReadRange(range); item.Type = RegisterType.Text; if (this.IsLarge) { vim.Register.SetRoll(item); } if (this.IsChange) { if (this.insertText === null) { vim.ApplyInsertMode(nextPosition); } } if (!this.IsOnlyYanc) { if (this.IsChange && this.insertText) { editor.ReplaceRange(range, this.insertText); editor.SetPosition(this.calcPositionAfterInsert(nextPosition)); } else { editor.DeleteRange(range, nextPosition); } } if (this.IsChange && this.insertText === null) { let startLine = editor.ReadLine(range.start.Line); let afterLineCount = editor.GetLastLineNum() + 1 - (range.end.Line - range.start.Line); vim.ApplyInsertMode(range.start); this.insertModeInfo = { DocumentLineCount: afterLineCount, Position: nextPosition, BeforeText: startLine.substring(0, range.start.Char), AfterText: endLine.substring(range.end.Char), }; } } private deleteLine(range: Range, editor: IEditor, vim: IVimStyle) { let del = new Range(); let nextPosition = new Position(); let nextPositionLineHasNoChar = false; nextPosition.Char = 0; let lastLine = editor.GetLastLineNum(); if (lastLine <= range.end.Line) { // delete to end line if (range.start.Line === 0) { // delete all del.start.Char = 0; del.start.Line = 0; del.end.Char = Number.MAX_VALUE; del.end.Line = range.end.Line; del.end = editor.UpdateValidPosition(del.end); nextPosition.Line = 0; } else if (this.IsChange) { // delete from home of start line del.start.Char = 0; del.start.Line = range.start.Line; del.start = editor.UpdateValidPosition(del.start); del.end.Char = Number.MAX_VALUE; del.end.Line = range.end.Line; del.end = editor.UpdateValidPosition(del.end); nextPosition.Line = del.start.Line; } else { // delete from end of previous line del.start.Char = Number.MAX_VALUE; del.start.Line = range.start.Line - 1; del.start = editor.UpdateValidPosition(del.start); del.end.Char = Number.MAX_VALUE; del.end.Line = range.end.Line; del.end = editor.UpdateValidPosition(del.end); nextPosition.Line = range.start.Line - 1; } } else { if (this.IsChange) { // delete from top of start line to end of end line del.start.Char = 0; del.start.Line = range.start.Line; del.end.Char = Number.MAX_VALUE; del.end.Line = range.end.Line; del.end = editor.UpdateValidPosition(del.end); nextPosition.Line = del.start.Line; } else { // delete to top of next line del.start.Char = 0; del.start.Line = range.start.Line; del.end.Char = 0; del.end.Line = range.end.Line + 1; nextPosition.Line = range.start.Line; } } let yanc = new Range(); yanc.start.Line = range.start.Line; yanc.start.Char = 0; yanc.end.Line = range.end.Line; yanc.end.Char = Number.MAX_VALUE; yanc.end = editor.UpdateValidPosition(yanc.end); let item = new RegisterItem(); item.Body = editor.ReadRange(yanc); if (this.IsLine) { item.Body += "\n"; } item.Type = RegisterType.LineText; vim.Register.SetRoll(item); if (!this.IsOnlyYanc) { if (this.IsChange && this.insertText !== null) { editor.ReplaceRange(del, this.insertText); } else { editor.DeleteRange(del, nextPosition); } } if (this.IsChange && this.insertText === null) { vim.ApplyInsertMode(); this.insertModeInfo = { DocumentLineCount: lastLine + 1, Position: nextPosition, BeforeText: "", AfterText: "", }; } } } /** * Nx */ export function DeleteCharactersUnderCursor(num: number): IAction { let m = new RightMotion(); m.Count = num === 0 ? 1 : num; let a = new DeleteYankChangeAction(); a.IsLarge = false; a.Motion = m; return a; } /** * NX */ export function DeleteCharactersBeforeCursor(num: number): IAction { let m = new RightMotion(); m.IsLeftDirection = true; m.Count = num === 0 ? 1 : num; let a = new DeleteYankChangeAction(); a.IsLarge = false; a.Motion = m; return a; } /** * dm */ export function DeleteTextWithMotion(num: number): IAction { return new DeleteYankChangeAction(); } /** * dd */ export function DeleteCurrentLine(num: number): IAction { let a = new DeleteYankChangeAction(); // let a = <DeleteYankChangeAction>action; // if (!(a.IsOnlyYanc == false && a.IsChange == false)) { // return null; // } a.IsLine = true; let m = new DownMotion(); m.Count = num === 0 ? 0 : num - 1; a.Motion = m; return a; } /** * D */ export function DeleteTextToEndOfLine(num: number): IAction { let m = new LastCharacterInLineMotion(); m.Count = 1; let a = new DeleteYankChangeAction(); a.IsLarge = false; a.Motion = m; return a; } /** * ym */ export function YankTextWithMotion(num: number): IAction { let a = new DeleteYankChangeAction(); a.IsOnlyYanc = true; return a; } /** * yy */ export function YankCurrentLine(num: number): IAction { let a = new DeleteYankChangeAction(); // let a = <DeleteYankChangeAction>action; // if (!(a.IsOnlyYanc == true)) { // this.Clear(); // return null; // } a.IsLine = true; a.IsOnlyYanc = true; let m = new DownMotion(); m.Count = num === 0 ? 0 : num - 1; a.Motion = m; return a; } /** * Y */ export function YankLine(num: number): IAction { let m = new LastCharacterInLineMotion(); m.Count = 1; let a = new DeleteYankChangeAction(); a.IsLarge = false; a.IsLine = true; a.Motion = m; a.IsOnlyYanc = true; return a; } /** * c{motion} */ export function ChangeTextWithMotion(num: number): IAction { let a = new DeleteYankChangeAction(); a.IsChange = true; return a; } /** * S */ export function ChangeLines(num: number): IAction { let m = new DownMotion(); m.Count = this.getNumStack() - 1; let a = new DeleteYankChangeAction(); a.IsLine = true; a.Motion = m; a.IsChange = true; return a; } /** * cc */ export function ChangeCurrentLine(num: number): IAction { let a = new DeleteYankChangeAction(); // let a = <DeleteYankChangeAction>action; // if (!(a.IsChange == true)) { // this.Clear(); // return null; // } a.IsLine = true; a.IsChange = true; let m = new DownMotion(); m.Count = num === 0 ? 0 : num - 1; a.Motion = m; return a; } /** * C */ export function ChangeTextToEndOfLine(num: number): IAction { let m = new LastCharacterInLineMotion(); m.Count = 1; let a = new DeleteYankChangeAction(); a.IsLarge = false; a.Motion = m; a.IsChange = true; return a; } /** * s */ export function ChangeCharacters(num: number): IAction { let m = new RightMotion(); m.Count = 1; let a = new DeleteYankChangeAction(); a.IsLarge = false; a.Motion = m; a.IsChange = true; return a; }
the_stack
import { Component, OnInit, ViewChild, OnDestroy, Input, QueryList, ViewChildren, TemplateRef, AfterViewInit, ChangeDetectorRef } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { FormBuilder, FormGroup } from '@angular/forms'; import { Ng2SmartTableComponent } from 'ng2-smart-table'; import { TranslateService } from '@ngx-translate/core'; import { NbDialogService, NbMenuItem, NbMenuService, NbPopoverDirective } from '@nebular/theme'; import { IInvoice, ITag, IOrganization, InvoiceTypeEnum, ComponentLayoutStyleEnum, InvoiceStatusTypesEnum, EstimateStatusTypesEnum, InvoiceColumnsEnum, EstimateColumnsEnum, IInvoiceEstimateHistory, PermissionsEnum, ICurrency, IInvoiceItemCreateInput, InvoiceTabsEnum, DiscountTaxTypeEnum } from '@gauzy/contracts'; import { distinctUntilChange, isNotEmpty } from '@gauzy/common-angular'; import { Router } from '@angular/router'; import { first, map, filter, tap, debounceTime } from 'rxjs/operators'; import { Subject, firstValueFrom } from 'rxjs'; import * as moment from 'moment'; import { NgxPermissionsService } from 'ngx-permissions'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import { DeleteConfirmationComponent } from '../../@shared/user/forms/delete-confirmation/delete-confirmation.component'; import { PaginationFilterBaseComponent } from '../../@shared/pagination/pagination-filter-base.component'; import { InvoiceSendMutationComponent } from './invoice-send/invoice-send-mutation.component'; import { InvoiceEstimateTotalValueComponent, InvoicePaidComponent } from './table-components'; import { ContactLinksComponent, DateViewComponent, NotesWithTagsComponent } from '../../@shared/table-components'; import { InvoiceEmailMutationComponent } from './invoice-email/invoice-email-mutation.component'; import { InvoiceDownloadMutationComponent } from './invoice-download/invoice-download-mutation.component'; import { API_PREFIX, ComponentEnum } from '../../@core/constants'; import { StatusBadgeComponent } from '../../@shared/status-badge/status-badge.component'; import { AddInternalNoteComponent } from './add-internal-note/add-internal-note.component'; import { PublicLinkComponent } from './public-link/public-link.component'; import { generateCsv } from '../../@shared/invoice/generate-csv'; import { InvoiceEstimateHistoryService, InvoiceItemService, InvoicesService, Store, ToastrService } from '../../@core/services'; import { ServerDataSource } from '../../@core/utils/smart-table/server.data-source'; @UntilDestroy({ checkProperties: true }) @Component({ selector: 'ngx-invoices', templateUrl: './invoices.component.html', styleUrls: ['invoices.component.scss'] }) export class InvoicesComponent extends PaginationFilterBaseComponent implements AfterViewInit, OnInit, OnDestroy { settingsSmartTable: object; smartTableSource: ServerDataSource; selectedInvoice: IInvoice; loading: boolean; disableButton = true; canBeSend = true; invoices: IInvoice[] = []; organization: IOrganization; viewComponentName: ComponentEnum; componentLayoutStyleEnum = ComponentLayoutStyleEnum; dataLayoutStyle = ComponentLayoutStyleEnum.TABLE; invoiceStatusTypes = Object.values(InvoiceStatusTypesEnum); estimateStatusTypes = Object.values(EstimateStatusTypesEnum); settingsContextMenu: NbMenuItem[]; contextMenus = []; columns: any; perPage: number = 10; histories: IInvoiceEstimateHistory[] = []; includeArchived = false; subject$: Subject<any> = new Subject(); invoiceTabsEnum = InvoiceTabsEnum; /* * getter setter for check esitmate or invoice */ private _isEstimate: boolean = false; @Input() set isEstimate(val: boolean) { this._isEstimate = val; } get isEstimate() { return this._isEstimate; } invoicesTable: Ng2SmartTableComponent; @ViewChild('invoicesTable') set content(content: Ng2SmartTableComponent) { if (content) { this.invoicesTable = content; this.onChangedSource(); } } @ViewChildren(NbPopoverDirective) public popups: QueryList<NbPopoverDirective>; /* * Search Tab Form */ public searchForm: FormGroup = InvoicesComponent.searchBuildForm(this.fb); static searchBuildForm(fb: FormBuilder): FormGroup { return fb.group({ invoiceNumber: [], organizationContact: [], invoiceDate: [], dueDate: [], totalValue: [], currency: [], status: [], tags: [] }); } /* * History Tab Form */ public historyForm: FormGroup = InvoicesComponent.historyBuildForm(this.fb); static historyBuildForm(fb: FormBuilder): FormGroup { return fb.group({ comment: [] }); } /* * Actions Buttons directive */ @ViewChild('actionButtons', { static : true }) actionButtons : TemplateRef<any>; constructor( private readonly fb: FormBuilder, public readonly translateService: TranslateService, private readonly store: Store, private readonly dialogService: NbDialogService, private readonly toastrService: ToastrService, private readonly invoicesService: InvoicesService, private readonly invoiceItemService: InvoiceItemService, private readonly router: Router, private readonly nbMenuService: NbMenuService, private readonly invoiceEstimateHistoryService: InvoiceEstimateHistoryService, private readonly ngxPermissionsService: NgxPermissionsService, private readonly httpClient: HttpClient, private readonly cdr: ChangeDetectorRef ) { super(translateService); } ngOnInit() { this.columns = this.getColumns(); this._applyTranslationOnSmartTable(); this._loadSmartTableSettings(); this.loadMenu(); this.setView(); } ngAfterViewInit() { this.subject$ .pipe( debounceTime(300), tap(() => this.loading = true), tap(() => this.cdr.detectChanges()), tap(() => this.getInvoices()), tap(() => this.clearItem()), untilDestroyed(this) ) .subscribe(); this.store.selectedOrganization$ .pipe( debounceTime(100), filter((organization) => !!organization), distinctUntilChange(), tap((organization) => (this.organization = organization)), tap(() => this.refreshPagination()), tap(() => this.subject$.next(true)), untilDestroyed(this) ) .subscribe(); } /* * Table on changed source event */ onChangedSource() { this.invoicesTable.source.onChangedSource .pipe( untilDestroyed(this), tap(() => this.clearItem()) ) .subscribe(); } setView() { this.viewComponentName = this.isEstimate ? ComponentEnum.ESTIMATES : ComponentEnum.INVOICES; this.store .componentLayout$(this.viewComponentName) .pipe( distinctUntilChange(), tap((componentLayout) => this.dataLayoutStyle = componentLayout), filter((componentLayout) => componentLayout === ComponentLayoutStyleEnum.CARDS_GRID), tap(() => this.refreshPagination()), tap(() => this.subject$.next(true)), untilDestroyed(this) ) .subscribe(); } loadMenu() { this.contextMenus = [ { title: this.getTranslation('INVOICES_PAGE.ACTION.DUPLICATE'), icon: 'copy-outline', permission: PermissionsEnum.INVOICES_EDIT }, { title: this.getTranslation('INVOICES_PAGE.ACTION.SEND'), icon: 'upload-outline', permission: PermissionsEnum.INVOICES_VIEW }, { title: this.getTranslation( 'INVOICES_PAGE.ACTION.CONVERT_TO_INVOICE' ), icon: 'swap', permission: PermissionsEnum.INVOICES_EDIT }, { title: this.getTranslation('INVOICES_PAGE.ACTION.EMAIL'), icon: 'email-outline', permission: PermissionsEnum.INVOICES_VIEW }, { title: this.getTranslation('INVOICES_PAGE.ACTION.DELETE'), icon: 'archive-outline', permission: PermissionsEnum.INVOICES_EDIT }, { title: this.getTranslation('INVOICES_PAGE.ACTION.NOTE'), icon: 'book-open-outline', permission: PermissionsEnum.INVOICES_EDIT } ]; if (!this.isEstimate) { this.contextMenus.push({ title: this.getTranslation('INVOICES_PAGE.ACTION.PAYMENTS'), icon: 'clipboard-outline', permission: PermissionsEnum.INVOICES_EDIT }); } const contextMenus = this.contextMenus.filter( (item) => this.ngxPermissionsService.getPermission(item.permission) != null ) if (this.isEstimate) { this.settingsContextMenu = contextMenus; } else { this.settingsContextMenu = contextMenus.filter( (item) => item.title !== this.getTranslation('INVOICES_PAGE.ACTION.CONVERT_TO_INVOICE') ); } this.nbMenuService.onItemClick().pipe(first()); } selectMenu(selectedItem?: IInvoice) { if (selectedItem) { this.selectInvoice({ isSelected: true, data: selectedItem }); } this.nbMenuService .onItemClick() .pipe( first(), map(({ item: { title } }) => title), untilDestroyed(this) ) .subscribe((title) => this.bulkAction(title)); } bulkAction(action: string) { if (action === this.getTranslation('INVOICES_PAGE.ACTION.DUPLICATE')) this.duplicated(this.selectedInvoice); if (action === this.getTranslation('INVOICES_PAGE.ACTION.SEND')) this.send(this.selectedInvoice); if ( action === this.getTranslation('INVOICES_PAGE.ACTION.CONVERT_TO_INVOICE') ) this.convert(this.selectedInvoice); if (action === this.getTranslation('INVOICES_PAGE.ACTION.EMAIL')) this.email(this.selectedInvoice); if (action === this.getTranslation('INVOICES_PAGE.ACTION.DELETE')) this.delete(this.selectedInvoice); if (action === this.getTranslation('INVOICES_PAGE.ACTION.PAYMENTS')) this.payments(); if (action === this.getTranslation('INVOICES_PAGE.ACTION.NOTE')) this.addInternalNote(); } add() { if (this.isEstimate) { this.router.navigate(['/pages/accounting/invoices/estimates/add']); } else { this.router.navigate(['/pages/accounting/invoices/add']); } } edit(selectedItem?: IInvoice) { this.invoicesService.changeValue(false); if (selectedItem) { this.selectInvoice({ isSelected: true, data: selectedItem }); } const { id } = this.selectedInvoice; if (this.isEstimate) { this.router.navigate([ `/pages/accounting/invoices/estimates/edit`, id ]); } else { this.router.navigate([ `/pages/accounting/invoices/edit`, id ]); } } async duplicated(selectedItem?: IInvoice) { this.invoicesService.changeValue(true); if (selectedItem) { this.selectInvoice({ isSelected: true, data: selectedItem }); } const { tenantId } = this.store.user; const { id: organizationId } = this.organization; const invoiceNumber = await this.invoicesService.getHighestInvoiceNumber(tenantId); const createdInvoice = await this.invoicesService.add({ invoiceNumber: +invoiceNumber['max'] + 1, invoiceDate: this.selectedInvoice.invoiceDate, dueDate: this.selectedInvoice.dueDate, currency: this.selectedInvoice.currency, discountValue: this.selectedInvoice.discountValue, discountType: this.selectedInvoice.discountType, tax: this.selectedInvoice.tax, tax2: this.selectedInvoice.tax2, taxType: this.selectedInvoice.taxType, tax2Type: this.selectedInvoice.tax2Type, terms: this.selectedInvoice.terms, paid: this.selectedInvoice.paid, totalValue: this.selectedInvoice.totalValue, organizationContactId: this.selectedInvoice.organizationContactId, toContact: this.selectedInvoice.toContact, organizationContactName: this.selectedInvoice.toContact?.name, fromOrganization: this.organization, organizationId, tenantId, invoiceType: this.selectedInvoice.invoiceType, tags: this.selectedInvoice.tags, isEstimate: this.isEstimate, status: this.selectedInvoice.status }); const invoiceItems: IInvoiceItemCreateInput[] = []; for (const item of this.selectedInvoice.invoiceItems) { const itemToAdd = { description: item.description, price: item.price, quantity: item.quantity, totalValue: item.totalValue, invoiceId: createdInvoice.id, tenantId, organizationId }; switch (this.selectedInvoice.invoiceType) { case InvoiceTypeEnum.BY_EMPLOYEE_HOURS: itemToAdd['employeeId'] = item.employeeId; break; case InvoiceTypeEnum.BY_PROJECT_HOURS: itemToAdd['projectId'] = item.projectId; break; case InvoiceTypeEnum.BY_TASK_HOURS: itemToAdd['taskId'] = item.taskId; break; case InvoiceTypeEnum.BY_PRODUCTS: itemToAdd['productId'] = item.productId; break; default: break; } invoiceItems.push(itemToAdd); } await this.invoiceItemService.createBulk( createdInvoice.id, invoiceItems ); const action = this.isEstimate ? this.getTranslation('INVOICES_PAGE.INVOICES_DUPLICATE_ESTIMATE') : this.getTranslation('INVOICES_PAGE.INVOICES_DUPLICATE_INVOICE'); await this.createInvoiceHistory(action); const { id } = createdInvoice; if (this.isEstimate) { this.toastrService.success('INVOICES_PAGE.INVOICES_DUPLICATE_ESTIMATE'); this.router.navigate([`/pages/accounting/invoices/estimates/edit`, id]); } else { this.toastrService.success('INVOICES_PAGE.INVOICES_DUPLICATE_INVOICE'); this.router.navigate([ `/pages/accounting/invoices/edit`, id ]); } } download(selectedItem?: IInvoice) { if (selectedItem) { this.selectInvoice({ isSelected: true, data: selectedItem }); } this.dialogService.open(InvoiceDownloadMutationComponent, { context: { invoice: this.selectedInvoice, isEstimate: this.isEstimate } }); } send(selectedItem?: IInvoice) { if (selectedItem) { this.selectInvoice({ isSelected: true, data: selectedItem }); } if (this.selectedInvoice.organizationContactId) { this.dialogService .open(InvoiceSendMutationComponent, { context: { invoice: this.selectedInvoice, isEstimate: this.isEstimate } }) .onClose .pipe( tap(() => this.subject$.next(true)), untilDestroyed(this) ) .subscribe(); } else { this.toastrService.warning('INVOICES_PAGE.SEND.NOT_LINKED'); } } async convert(selectedItem?: IInvoice) { if (selectedItem) { this.selectInvoice({ isSelected: true, data: selectedItem }); } const { id: invoiceId } = this.selectedInvoice; await this.invoicesService.update(invoiceId, { isEstimate: false, status: InvoiceStatusTypesEnum.DRAFT }); const action = this.getTranslation('INVOICES_PAGE.ESTIMATES.CONVERTED_TO_INVOICE'); await this.createInvoiceHistory(action); this.toastrService.success('INVOICES_PAGE.ESTIMATES.ESTIMATE_CONVERT'); this.subject$.next(true); } async delete(selectedItem?: IInvoice) { if (selectedItem) { this.selectInvoice({ isSelected: true, data: selectedItem }); } const result = await firstValueFrom(this.dialogService .open(DeleteConfirmationComponent) .onClose); if (result) { const { id } = this.selectedInvoice; await this.invoicesService.delete(id); if (this.isEstimate) { this.toastrService.success('INVOICES_PAGE.INVOICES_DELETE_ESTIMATE'); } else { this.toastrService.success('INVOICES_PAGE.INVOICES_DELETE_INVOICE'); } this.subject$.next(true); } } view() { const { id } = this.selectedInvoice; if (this.isEstimate) { this.router.navigate([ `/pages/accounting/invoices/estimates/view`, id ]); } else { this.router.navigate([ `/pages/accounting/invoices/view`, id ]); } } email(selectedItem?: IInvoice) { if (selectedItem) { this.selectInvoice({ isSelected: true, data: selectedItem }); } this.dialogService .open(InvoiceEmailMutationComponent, { context: { invoice: this.selectedInvoice, isEstimate: this.isEstimate } }) .onClose .pipe( tap(() => this.subject$.next(true)), untilDestroyed(this) ) .subscribe(); } payments() { const { id } = this.selectedInvoice; this.router.navigate([ `/pages/accounting/invoices/payments`, id ]); } addInternalNote() { this.dialogService .open(AddInternalNoteComponent, { context: { invoice: this.selectedInvoice } }) .onClose .pipe( tap(() => this.subject$.next(true)), untilDestroyed(this) ) .subscribe(); } exportToCsv(selectedItem) { if (selectedItem) { this.selectInvoice({ isSelected: true, data: selectedItem }); } let fileName: string; const { invoiceNumber, invoiceDate, dueDate, status, totalValue, tax, tax2, discountValue, toContact, isEstimate } = this.selectedInvoice; if (isEstimate) { fileName = `${this.getTranslation('INVOICES_PAGE.ESTIMATE')}-${invoiceNumber}`; } else { fileName = `${this.getTranslation('INVOICES_PAGE.INVOICE')}-${invoiceNumber}`; } const data = [{ invoiceNumber, invoiceDate, dueDate, status: `${this.getTranslation(`INVOICES_PAGE.STATUSES.${status}`)}`, totalValue, tax, tax2, discountValue, contact: toContact.name }]; const headers = [ isEstimate ? this.getTranslation('INVOICES_PAGE.ESTIMATE_NUMBER') : this.getTranslation('INVOICES_PAGE.INVOICE_NUMBER'), isEstimate ? this.getTranslation('INVOICES_PAGE.ESTIMATE_DATE') : this.getTranslation('INVOICES_PAGE.INVOICE_DATE'), this.getTranslation('INVOICES_PAGE.DUE_DATE'), this.getTranslation('INVOICES_PAGE.STATUS'), this.getTranslation('INVOICES_PAGE.TOTAL_VALUE'), this.getTranslation('INVOICES_PAGE.TAX'), this.getTranslation('INVOICES_PAGE.TAX_2'), this.getTranslation('INVOICES_PAGE.INVOICES_SELECT_DISCOUNT_VALUE'), this.getTranslation('INVOICES_PAGE.CONTACT') ].join(','); generateCsv(data, headers, fileName); } /* * Register Smart Table Source Config */ setSmartTableSource() { const { tenantId } = this.store.user; const { id: organizationId } = this.organization; this.smartTableSource = new ServerDataSource(this.httpClient, { endPoint: `${API_PREFIX}/invoices/pagination`, relations: [ 'invoiceItems', 'invoiceItems.employee', 'invoiceItems.employee.user', 'invoiceItems.project', 'invoiceItems.product', 'invoiceItems.invoice', 'invoiceItems.expense', 'invoiceItems.task', 'tags', 'payments', 'fromOrganization', 'toContact', 'historyRecords', 'historyRecords.user' ], join: { alias: "invoice", leftJoin: { toContact: 'invoice.toContact', tags: 'invoice.tags' }, ...(this.filters.join) ? this.filters.join : {} }, where: { organizationId, tenantId, isEstimate: (this.isEstimate === true) ? 1 : 0, isArchived: (this.includeArchived === true) ? 1 : 0, ...this.filters.where }, resultMap: (invoice: IInvoice) => { return Object.assign({}, invoice, { organizationContactName: (invoice.toContact) ? invoice.toContact.name : null, status: this.statusMapper(invoice.status), tax: (DiscountTaxTypeEnum.PERCENT === invoice.taxType) ? `${invoice.tax}%` : `${invoice.tax}`, tax2: (DiscountTaxTypeEnum.PERCENT === invoice.tax2Type) ? `${invoice.tax2}%` : `${invoice.tax2}`, discountValue: (DiscountTaxTypeEnum.PERCENT === invoice.discountType) ? `${invoice.discountValue}%` : `${invoice.discountValue}`, }); }, finalize: () => { this.loading = false; } }); } async getInvoices() { if (!this.organization) { return; } try { this.setSmartTableSource(); if (this.dataLayoutStyle === ComponentLayoutStyleEnum.CARDS_GRID) { // Initiate GRID view pagination const { activePage, itemsPerPage } = this.pagination; this.smartTableSource.setPaging(activePage, itemsPerPage, false); await this.smartTableSource.getElements(); this.invoices = this.smartTableSource.getData(); this.pagination['totalItems'] = this.smartTableSource.count(); } } catch (error) { this.toastrService.danger( this.getTranslation('NOTES.INVOICE.INVOICE_ERROR', { error: error.error.message || error.message }), this.getTranslation('TOASTR.TITLE.ERROR') ); } } async addComment(historyFormDirective) { const { comment } = this.historyForm.value; const { id: invoiceId } = this.selectedInvoice; if (comment) { const action = comment; await this.createInvoiceHistory(action); historyFormDirective.resetForm(); this.historyForm.reset(); const invoice = await this.invoicesService.getById(invoiceId, [ 'invoiceItems', 'invoiceItems.employee', 'invoiceItems.employee.user', 'invoiceItems.project', 'invoiceItems.product', 'invoiceItems.invoice', 'invoiceItems.expense', 'invoiceItems.task', 'tags', 'payments', 'fromOrganization', 'toContact', 'historyRecords', 'historyRecords.user' ]); if(this.dataLayoutStyle === ComponentLayoutStyleEnum.TABLE) { this.invoicesTable.grid.getRows().map((row) => { if (row['data']['id'] === invoice.id) { row['data'] = invoice; row.isSelected = true; } else { row.isSelected = false; } return row; }); } else { this.invoices = this.invoices.map((row: IInvoice) => { if (row.id === invoice.id) { return invoice; } return row; }); } this.selectInvoice({ isSelected: true, data: invoice }); } } async generatePublicLink(selectedItem) { if (selectedItem) { this.selectInvoice({ isSelected: true, data: selectedItem }); } this.dialogService.open(PublicLinkComponent, { context: { invoice: this.selectedInvoice } }); } async archive() { await this.invoicesService.update(this.selectedInvoice.id, { isArchived: true }); this.subject$.next(true); } async selectInvoice({ isSelected, data }) { this.disableButton = !isSelected; this.selectedInvoice = isSelected ? data : null; if(isSelected){ this.canBeSend = data.toContact ? isSelected : !isSelected; }else{ this.canBeSend = isSelected; } if (isSelected) { const { historyRecords = [] } = data; const histories = []; historyRecords.forEach((h: IInvoiceEstimateHistory) => { const history = { id: h.id, createdAt: new Date(h.createdAt).toString().slice(0, 24), action: h.action, user: h.user }; histories.push(history); }); histories.sort(function (a, b) { return +new Date(b.createdAt) - +new Date(a.createdAt); }); this.histories = histories; } } private statusMapper = (value: string) => { let badgeClass; if (value) { badgeClass = [ 'sent', 'viewed', 'accepted', 'active', 'fully paid' ].includes(value.toLowerCase()) ? 'success' : ['void', 'draft', 'partially paid'].includes( value.toLowerCase() ) ? 'warning' : 'danger'; } return { text: this.getTranslation(`INVOICES_PAGE.STATUSES.${value.toUpperCase()}`), class: badgeClass }; } private _loadSmartTableSettings() { this.settingsSmartTable = { pager: { display: true, perPage: this.perPage ? this.perPage : 10 }, hideSubHeader: true, actions: false, mode: 'external', editable: true, noDataMessage: this.getTranslation('SM_TABLE.NO_DATA'), columns: { invoiceNumber: { title: this.isEstimate ? this.getTranslation('INVOICES_PAGE.ESTIMATES.ESTIMATE_NUMBER') : this.getTranslation('INVOICES_PAGE.INVOICE_NUMBER'), type: 'custom', sortDirection: 'asc', width: '10%', renderComponent: NotesWithTagsComponent } } }; if ( this.columns.includes(InvoiceColumnsEnum.INVOICE_DATE) || this.columns.includes(EstimateColumnsEnum.ESTIMATE_DATE) ) { this.settingsSmartTable['columns']['invoiceDate'] = { title: this.isEstimate ? this.getTranslation('INVOICES_PAGE.ESTIMATE_DATE') : this.getTranslation('INVOICES_PAGE.INVOICE_DATE'), type: 'custom', width: '10%', filter: false, renderComponent: DateViewComponent }; } if (this.columns.includes(InvoiceColumnsEnum.DUE_DATE)) { this.settingsSmartTable['columns']['dueDate'] = { title: this.getTranslation('INVOICES_PAGE.DUE_DATE'), type: 'custom', width: '10%', filter: false, renderComponent: DateViewComponent }; } if (this.columns.includes(InvoiceColumnsEnum.STATUS)) { this.settingsSmartTable['columns']['status'] = { title: this.getTranslation('INVOICES_PAGE.STATUS'), type: 'custom', width: '5%', renderComponent: StatusBadgeComponent, filter: false }; } if (this.columns.includes(InvoiceColumnsEnum.TOTAL_VALUE)) { this.settingsSmartTable['columns']['totalValue'] = { title: this.getTranslation('INVOICES_PAGE.TOTAL_VALUE'), type: 'custom', renderComponent: InvoiceEstimateTotalValueComponent, filter: false, width: '10%' }; } if (this.columns.includes(InvoiceColumnsEnum.TAX)) { this.settingsSmartTable['columns']['tax'] = { title: this.getTranslation('INVOICES_PAGE.TAX'), type: 'text', width: '5%', filter: false }; } if (this.columns.includes(InvoiceColumnsEnum.TAX_2)) { this.settingsSmartTable['columns']['tax2'] = { title: this.getTranslation('INVOICES_PAGE.TAX_2'), type: 'text', width: '5%', filter: false }; } if (this.columns.includes(InvoiceColumnsEnum.DISCOUNT)) { this.settingsSmartTable['columns']['discountValue'] = { title: this.getTranslation( 'INVOICES_PAGE.INVOICES_SELECT_DISCOUNT_VALUE' ), type: 'text', width: '5%', filter: false }; } if (this.columns.includes(InvoiceColumnsEnum.CONTACT)) { this.settingsSmartTable['columns']['toContact'] = { title: this.getTranslation('INVOICES_PAGE.CONTACT'), type: 'custom', width: '12%', filter: false, sort: false, renderComponent: ContactLinksComponent, }; } if (!this.isEstimate) { if (this.columns.includes(InvoiceColumnsEnum.PAID_STATUS)) { this.settingsSmartTable['columns']['paid'] = { title: this.getTranslation('INVOICES_PAGE.PAID_STATUS'), type: 'custom', width: '20%', renderComponent: InvoicePaidComponent, filter: false }; } } } showPerPage() { if ( this.perPage && Number.isInteger(this.perPage) && this.perPage > 0 ) { const { page } = this.smartTableSource.getPaging(); this.pagination = Object.assign({}, this.pagination, { activePage: page, itemsPerPage: this.perPage }); if (this.dataLayoutStyle === ComponentLayoutStyleEnum.CARDS_GRID) { this.subject$.next(true); } else { this.smartTableSource.setPaging(page, this.perPage, false); this._loadSmartTableSettings(); } } } search() { const { dueDate, invoiceNumber, invoiceDate, totalValue, currency, status, organizationContact, tags = [] } = this.searchForm.value; if (invoiceNumber) { this.setFilter({ field: 'invoiceNumber', search: invoiceNumber }, false); } if (invoiceDate) { this.setFilter({ field: 'invoiceDate', search: moment(invoiceDate).format('YYYY-MM-DD') }, false); } if (dueDate) { this.setFilter({ field: 'dueDate', search: moment(dueDate).format('YYYY-MM-DD') }, false); } if (totalValue) { this.setFilter({ field: 'totalValue', search: totalValue }, false); } if (currency) { this.setFilter({ field: 'currency', search: currency }, false); } if (status) { this.setFilter({ field: 'status', search: status }, false); } if (organizationContact) { this.setFilter({ field: 'toContact', search: [organizationContact.id] }, false); } if (isNotEmpty(tags)) { const tagIds = []; for (const tag of tags) { tagIds.push(tag.id); } this.setFilter({ field: 'tags', search: tagIds }); } if (isNotEmpty(this.filters)) { this.refreshPagination(); this.subject$.next(true); } } toggleIncludeArchived(event) { this.includeArchived = event; this.subject$.next(true); } reset() { this.searchForm.reset(); this._filters = {}; this.subject$.next(true); } selectedTagsEvent(currentTagSelection: ITag[]) { this.searchForm.patchValue({ tags: currentTagSelection }); } async selectStatus($event) { await this.invoicesService.update(this.selectedInvoice.id, { status: $event }); this.subject$.next(true); } selectColumn($event: string[]) { this.columns = $event; this._loadSmartTableSettings(); } toggleActionsPopover() { this.popups.first.toggle(); this.popups.last.hide(); } toggleTableSettingsPopover() { this.popups.last.toggle(); if (this.popups.length > 1) { this.popups.first.hide(); } } closeActionsPopover() { const actionsPopup = this.popups.first; const settingsPopup = this.popups.last; if(settingsPopup.isShown){ settingsPopup.hide(); } if (actionsPopup.isShown) { actionsPopup.hide(); } } private _applyTranslationOnSmartTable() { this.translateService.onLangChange .pipe( tap(() => this._loadSmartTableSettings()), untilDestroyed(this) ) .subscribe(); } onChangeTab(event) { this.closeActionsPopover(); } clearItem() { this.selectInvoice({ isSelected: false, data: null }); this.deselectAll(); } /* * Deselect all table rows */ deselectAll() { if (this.invoicesTable && this.invoicesTable.grid) { this.invoicesTable.grid.dataSet['willSelect'] = 'false'; this.invoicesTable.grid.dataSet.deselectAll(); } } getColumns(): string[] { if (this.isEstimate) { return Object.values(EstimateColumnsEnum); } return Object.values(InvoiceColumnsEnum); } /* * Create Invoice History Event */ async createInvoiceHistory(action: string) { const { tenantId, id: userId } = this.store.user; const { id: organizationId } = this.organization; const { id: invoiceId } = this.selectedInvoice; await this.invoiceEstimateHistoryService.add({ action, invoice: this.selectedInvoice, invoiceId, user: this.store.user, userId, organization: this.organization, organizationId, tenantId }); } /* * On Changed Currency Event Emitter */ currencyChanged($event: ICurrency) { } ngOnDestroy() { } }
the_stack
import { generateMnemonic as bip39GenerateMnemonic, mnemonicToSeed, } from 'bip39'; import pbkdf2 from 'pbkdf2'; import sodium from 'libsodium-wrappers-sumo'; import elliptic from 'elliptic'; import { b58cdecode, b58cencode, hex2buf, mergebuf, buf2hex } from './utility'; import { prefix } from './constants'; interface Keys { pk: string; pkh: string; sk: string; esk?: string; salt?: Uint8Array; } interface KeysMnemonicPassphrase { mnemonic: string; passphrase?: string; sk: string; pk: string; pkh: string; } interface Signed { bytes: string; magicBytes: string; sig: string; prefixSig: string; sbytes: string; } /** * @description Extract key pairs from a secret key * @param {string} sk The secret key to extract key pairs from * @param {string} [passphrase] The password used to encrypt the sk * @returns {Promise} The extracted key pairs * @example * cryptoUtils.extractKeys('edskRqAF8s2MKKqRMxq53CYYLMnrqvokMyrtmPRFd5H9osc4bFmqKBY119jiiqKQMti2frLAoKGgZSQN3Lc3ybf5sgPUy38e5A') * .then(({ sk, pk, pkh }) => console.log(sk, pk, pkh)); */ export const extractKeys = async ( sk: string, passphrase = '', ): Promise<Keys> => { await sodium.ready; const curve = sk.substring(0, 2); if (![54, 55, 88, 98].includes(sk.length)) { throw new Error('Invalid length for a key encoding'); } const encrypted = sk.substring(2, 3) === 'e'; let constructedKey = b58cdecode( sk, prefix[`${curve}${encrypted ? 'e' : ''}sk`], ); let salt; if (encrypted) { salt = constructedKey.slice(0, 8); const encryptedSk = constructedKey.slice(8); if (!passphrase) { throw new Error('No passphrase was provided to decrypt the key'); } const key = pbkdf2.pbkdf2Sync(passphrase, salt, 32768, 32, 'sha512'); constructedKey = sodium.crypto_secretbox_open_easy( new Uint8Array(encryptedSk), new Uint8Array(24), new Uint8Array(key), ); } let secretKey = new Uint8Array(constructedKey); let privateKeys: { sk: string; esk?: string; salt?: Uint8Array } = { sk, }; if (encrypted) { privateKeys = { esk: sk, sk: b58cencode(secretKey, prefix[`${curve}sk`]), salt, }; } if (curve === 'ed') { let publicKey; if (constructedKey.length === 64) { publicKey = new Uint8Array( sodium.crypto_sign_ed25519_sk_to_pk(secretKey), ); } else { const { publicKey: publicKeyDerived, privateKey, } = sodium.crypto_sign_seed_keypair(secretKey, 'uint8array'); publicKey = new Uint8Array(publicKeyDerived); secretKey = new Uint8Array(privateKey); if (encrypted) { privateKeys = { esk: sk, sk: b58cencode(secretKey, prefix[`${curve}sk`]), salt, }; } } return { ...privateKeys, pk: b58cencode(publicKey, prefix.edpk), pkh: b58cencode(sodium.crypto_generichash(20, publicKey), prefix.tz1), }; } if (curve === 'sp') { const keyPair = new elliptic.ec('secp256k1').keyFromPrivate(constructedKey); const prefixVal = keyPair.getPublic().getY().toArray()[31] % 2 ? 3 : 2; const pad = new Array(32).fill(0); const publicKey = new Uint8Array( [prefixVal].concat( pad.concat(keyPair.getPublic().getX().toArray()).slice(-32), ), ); return { ...privateKeys, pk: b58cencode(publicKey, prefix.sppk), pkh: b58cencode( sodium.crypto_generichash(20, new Uint8Array(publicKey)), prefix.tz2, ), }; } if (curve === 'p2') { const keyPair = new elliptic.ec('p256').keyFromPrivate(constructedKey); const prefixVal = keyPair.getPublic().getY().toArray()[31] % 2 ? 3 : 2; const pad = new Array(32).fill(0); const publicKey = new Uint8Array( [prefixVal].concat( pad.concat(keyPair.getPublic().getX().toArray()).slice(-32), ), ); return { ...privateKeys, pk: b58cencode(publicKey, prefix.p2pk), pkh: b58cencode( sodium.crypto_generichash(20, new Uint8Array(publicKey)), prefix.tz3, ), }; } throw new Error('Invalid prefix for a key encoding'); }; /** * @description Generate a mnemonic * @returns {string} The 15 word generated mnemonic */ export const generateMnemonic = (): string => bip39GenerateMnemonic(160); /** * @description Check the validity of a tezos implicit address (tz1...) * @param {string} address The address to check * @returns {boolean} Whether address is valid or not */ export const checkAddress = (address: string): boolean => { try { b58cdecode(address, prefix.tz1); return true; } catch (e) { return false; } }; /** * @description Generate a new key pair given a mnemonic and passphrase * @param {string} mnemonic The mnemonic seed * @param {string} passphrase The passphrase used to encrypt the seed * @returns {Promise} The generated key pair * @example * cryptoUtils.generateKeys('raw peace visual boil prefer rebel anchor right elegant side gossip enroll force salmon between', 'my_password_123') * .then(({ mnemonic, passphrase, sk, pk, pkh }) => console.log(mnemonic, passphrase, sk, pk, pkh)); */ export const generateKeys = async ( mnemonic: string, passphrase?: string, ): Promise<KeysMnemonicPassphrase> => { await sodium.ready; const s = await mnemonicToSeed(mnemonic, passphrase).then((seed) => seed.slice(0, 32), ); const kp = sodium.crypto_sign_seed_keypair(new Uint8Array(s)); return { mnemonic, passphrase, sk: b58cencode(kp.privateKey, prefix.edsk), pk: b58cencode(kp.publicKey, prefix.edpk), pkh: b58cencode(sodium.crypto_generichash(20, kp.publicKey), prefix.tz1), }; }; /** * @description Encrypts a secret key with a passphrase * @param {string} key The secret key * @param {string} passphrase The passphrase to encrypt the key * @param {Uint8Array} salt The salt to apply to the encryption * @returns {string} The encrypted secret key * @example * const encryptedSecretKey = cryptoUtils.encryptSecretKey( * 'p2sk3T9fYpibobxRr7daoPzywLpLAXJVd3bkXpAaqYVtVB37aAp7bU', * 'password', * ); */ export const encryptSecretKey = ( key: string, passphrase: string, salt: Uint8Array = sodium.randombytes_buf(8), ) => { if (!passphrase) { throw new Error('passphrase is require when encrypting a secret key'); } const curve = key.substring(0, 2); let secretKey = b58cdecode(key, prefix[`${curve}sk`]); if (curve === 'ed') { if (secretKey.length !== 64) { // seed const { privateKey } = sodium.crypto_sign_seed_keypair( secretKey, 'uint8array', ); secretKey = new Uint8Array(privateKey); } } if (curve === 'ed') { secretKey = sodium.crypto_sign_ed25519_sk_to_seed(secretKey, 'uint8array'); } const encryptionKey = pbkdf2.pbkdf2Sync( passphrase, salt, 32768, 32, 'sha512', ); const encryptedSk = sodium.crypto_secretbox_easy( secretKey, new Uint8Array(24), new Uint8Array(encryptionKey), ); return b58cencode(mergebuf(salt, encryptedSk), prefix[`${curve}esk`]); }; /** * @description Sign bytes * @param {string} bytes The bytes to sign * @param {string} sk The secret key to sign the bytes with * @param {Object} magicBytes The magic bytes for the operation * @param {string} [password] The password used to encrypt the sk * @returns {Promise} The signed bytes * @example * import { magicBytes as magicBytesMap } from 'sotez'; * * cryptoUtils.sign(opbytes, keys.sk, magicBytesMap.generic) * .then(({ bytes, magicBytes, sig, prefixSig, sbytes }) => console.log(bytes, magicBytes, sig, prefixSig, sbytes)); */ export const sign = async ( bytes: string, sk: string, magicBytes?: Uint8Array, password = '', ): Promise<Signed> => { await sodium.ready; const curve = sk.substring(0, 2); if (![54, 55, 88, 98].includes(sk.length)) { throw new Error('Invalid length for a key encoding'); } const encrypted = sk.substring(2, 3) === 'e'; let constructedKey = b58cdecode( sk, prefix[`${curve}${encrypted ? 'e' : ''}sk`], ); if (encrypted) { const salt = constructedKey.slice(0, 8); const encryptedSk = constructedKey.slice(8); if (!password) { throw new Error('No password was provided to decrypt the key'); } const key = pbkdf2.pbkdf2Sync(password, salt, 32768, 32, 'sha512'); constructedKey = sodium.crypto_secretbox_open_easy( new Uint8Array(encryptedSk), new Uint8Array(24), new Uint8Array(key), ); } let secretKey = new Uint8Array(constructedKey); let bb = hex2buf(bytes); if (typeof magicBytes !== 'undefined') { bb = mergebuf(magicBytes, bb); } const bytesHash = new Uint8Array(sodium.crypto_generichash(32, bb)); if (curve === 'ed') { if (constructedKey.length !== 64) { const { privateKey } = sodium.crypto_sign_seed_keypair( secretKey, 'uint8array', ); secretKey = new Uint8Array(privateKey); } const signature = sodium.crypto_sign_detached(bytesHash, secretKey); const sbytes = bytes + buf2hex(signature); return { bytes, magicBytes: magicBytes ? buf2hex(magicBytes) : '', sig: b58cencode(signature, prefix.sig), prefixSig: b58cencode(signature, prefix.edsig), sbytes, }; } if (curve === 'sp') { const key = new elliptic.ec('secp256k1').keyFromPrivate(secretKey); const sig = key.sign(bytesHash, { canonical: true }); const signature = new Uint8Array( sig.r.toArray(undefined, 32).concat(sig.s.toArray(undefined, 32)), ); const sbytes = bytes + buf2hex(signature); return { bytes, magicBytes: magicBytes ? buf2hex(magicBytes) : '', sig: b58cencode(signature, prefix.sig), prefixSig: b58cencode(signature, prefix.spsig), sbytes, }; } if (curve === 'p2') { const key = new elliptic.ec('p256').keyFromPrivate(secretKey); const sig = key.sign(bytesHash, { canonical: true }); const signature = new Uint8Array( sig.r.toArray(undefined, 32).concat(sig.s.toArray(undefined, 32)), ); const sbytes = bytes + buf2hex(signature); return { bytes, magicBytes: magicBytes ? buf2hex(magicBytes) : '', sig: b58cencode(signature, prefix.sig), prefixSig: b58cencode(signature, prefix.p2sig), sbytes, }; } throw new Error('Provided curve not supported'); }; /** * @description Verify signed bytes * @param {string} bytes The signed bytes * @param {string} sig The signature of the signed bytes * @param {string} pk The public key * @returns {boolean} Whether the signed bytes are valid */ export const verify = async ( bytes: string, sig: string, pk: string, ): Promise<boolean> => { await sodium.ready; if (!pk) { throw new Error('Cannot verify without a public key'); } const curve = pk.substring(0, 2); const publicKey = new Uint8Array(b58cdecode(pk, prefix[`${curve}pk`])); if (sig.substring(0, 3) !== 'sig') { if (curve !== sig.substring(0, 2)) { // 'sp', 'p2' 'ed' throw new Error('Signature and public key curves mismatch.'); } } const bytesBuffer = sodium.crypto_generichash(32, hex2buf(bytes)); let signature; if (sig.substring(0, 3) === 'sig') { signature = b58cdecode(sig, prefix.sig); } else if (sig.substring(0, 5) === `${curve}sig`) { signature = b58cdecode(sig, prefix[`${curve}sig`]); } else { throw new Error(`Invalid signature provided: ${sig}`); } if (curve === 'ed') { try { return sodium.crypto_sign_verify_detached( new Uint8Array(signature), new Uint8Array(bytesBuffer), publicKey, ); } catch (e) { return false; } } else if (curve === 'sp') { const key = new elliptic.ec('secp256k1').keyFromPublic(publicKey); const formattedSig = buf2hex(signature); const match = formattedSig.match(/([a-f\d]{64})/gi); if (match) { try { const [r, s] = match; return key.verify(bytesBuffer, { r, s }); } catch (e) { return false; } } return false; } else if (curve === 'p2') { const key = new elliptic.ec('p256').keyFromPublic(publicKey); const formattedSig = buf2hex(signature); const match = formattedSig.match(/([a-f\d]{64})/gi); if (match) { try { const [r, s] = match; return key.verify(bytesBuffer, { r, s }); } catch (e) { return false; } } return false; } else { throw new Error(`Curve '${curve}' not supported`); } }; export default { extractKeys, encryptSecretKey, generateKeys, checkAddress, generateMnemonic, sign, verify, };
the_stack
import { fromJS, List, Map, merge, mergeDeep, mergeDeepWith, Record, Set, } from 'immutable'; describe('merge', () => { it('merges two maps', () => { const m1 = Map({ a: 1, b: 2, c: 3 }); const m2 = Map({ d: 10, b: 20, e: 30 }); expect(m1.merge(m2)).toEqual(Map({ a: 1, b: 20, c: 3, d: 10, e: 30 })); }); it('can merge in an explicitly undefined value', () => { const m1 = Map({ a: 1, b: 2 }); const m2 = Map({ a: undefined as any }); expect(m1.merge(m2)).toEqual(Map({ a: undefined, b: 2 })); }); it('merges two maps with a merge function', () => { const m1 = Map({ a: 1, b: 2, c: 3 }); const m2 = Map({ d: 10, b: 20, e: 30 }); expect(m1.mergeWith((a: any, b: any) => a + b, m2)).toEqual( Map({ a: 1, b: 22, c: 3, d: 10, e: 30 }) ); }); it('throws typeError without merge function', () => { const m1 = Map({ a: 1, b: 2, c: 3 }); const m2 = Map({ d: 10, b: 20, e: 30 }); // @ts-expect-error expect(() => m1.mergeWith(1, m2)).toThrowError(TypeError); }); it('provides key as the third argument of merge function', () => { const m1 = Map({ id: 'temp', b: 2, c: 3 }); const m2 = Map({ id: 10, b: 20, e: 30 }); const add = (a: any, b: any) => a + b; expect( m1.mergeWith((a, b, key) => (key !== 'id' ? add(a, b) : b), m2) ).toEqual(Map({ id: 10, b: 22, c: 3, e: 30 })); }); it('deep merges two maps', () => { const m1 = fromJS({ a: { b: { c: 1, d: 2 } } }) as Map<string, any>; const m2 = fromJS({ a: { b: { c: 10, e: 20 }, f: 30 }, g: 40 }); expect(m1.mergeDeep(m2)).toEqual( fromJS({ a: { b: { c: 10, d: 2, e: 20 }, f: 30 }, g: 40 }) ); }); it('merge uses === for return-self optimization', () => { const date1 = new Date(1234567890000); // Value equal, but different reference. const date2 = new Date(1234567890000); const m = Map().set('a', date1); expect(m.merge({ a: date2 })).not.toBe(m); expect(m.merge({ a: date1 })).toBe(m); }); it('deep merge uses === for return-self optimization', () => { const date1 = new Date(1234567890000); // Value equal, but different reference. const date2 = new Date(1234567890000); const m = Map().setIn(['a', 'b', 'c'], date1); expect(m.mergeDeep({ a: { b: { c: date2 } } })).not.toBe(m); expect(m.mergeDeep({ a: { b: { c: date1 } } })).toBe(m); }); it('deep merges raw JS', () => { const m1 = fromJS({ a: { b: { c: 1, d: 2 } } }) as Map<string, any>; const js = { a: { b: { c: 10, e: 20 }, f: 30 }, g: 40 }; expect(m1.mergeDeep(js)).toEqual( fromJS({ a: { b: { c: 10, d: 2, e: 20 }, f: 30 }, g: 40 }) ); }); it('deep merges raw JS with a merge function', () => { const m1 = fromJS({ a: { b: { c: 1, d: 2 } } }) as Map<string, any>; const js = { a: { b: { c: 10, e: 20 }, f: 30 }, g: 40 }; expect(m1.mergeDeepWith((a: any, b: any) => a + b, js)).toEqual( fromJS({ a: { b: { c: 11, d: 2, e: 20 }, f: 30 }, g: 40 }) ); }); it('deep merges raw JS into raw JS with a merge function', () => { const js1 = { a: { b: { c: 1, d: 2 } } }; const js2 = { a: { b: { c: 10, e: 20 }, f: 30 }, g: 40 }; expect(mergeDeepWith((a: any, b: any) => a + b, js1, js2)).toEqual({ a: { b: { c: 11, d: 2, e: 20 }, f: 30 }, g: 40, }); }); it('deep merges collections into raw JS with a merge function', () => { const js = { a: { b: { c: 1, d: 2 } } }; const m = fromJS({ a: { b: { c: 10, e: 20 }, f: 30 }, g: 40 }); expect(mergeDeepWith((a: any, b: any) => a + b, js, m)).toEqual({ a: { b: { c: 11, d: 2, e: 20 }, f: 30 }, g: 40, }); }); it('returns self when a deep merges is a no-op', () => { const m1 = fromJS({ a: { b: { c: 1, d: 2 } } }) as Map<string, any>; expect(m1.mergeDeep({ a: { b: { c: 1 } } })).toBe(m1); }); it('returns arg when a deep merges is a no-op', () => { const m1 = fromJS({ a: { b: { c: 1, d: 2 } } }); expect(Map().mergeDeep(m1)).toBe(m1); }); it('returns self when a deep merges is a no-op on raw JS', () => { const m1 = { a: { b: { c: 1, d: 2 } } }; expect(mergeDeep(m1, { a: { b: { c: 1 } } })).toBe(m1); }); it('can overwrite existing maps', () => { expect( ( fromJS({ a: { x: 1, y: 1 }, b: { x: 2, y: 2 } }) as Map<string, any> ).merge({ a: null, b: Map({ x: 10 }), }) ).toEqual(fromJS({ a: null, b: { x: 10 } })); expect( ( fromJS({ a: { x: 1, y: 1 }, b: { x: 2, y: 2 } }) as Map<string, any> ).mergeDeep({ a: null, b: { x: 10 }, }) ).toEqual(fromJS({ a: null, b: { x: 10, y: 2 } })); }); it('can overwrite existing maps with objects', () => { const m1 = fromJS({ a: { x: 1, y: 1 } }) as Map<string, any>; // deep conversion. const m2 = Map({ a: { z: 10 } }); // shallow conversion to Map. // Raw object simply replaces map. expect(m1.merge(m2).get('a')).toEqual({ z: 10 }); // raw object. // However, mergeDeep will merge that value into the inner Map. expect(m1.mergeDeep(m2).get('a')).toEqual(Map({ x: 1, y: 1, z: 10 })); }); it('merges map entries with List and Set values', () => { const initial = Map({ a: Map({ x: 10, y: 20 }), b: List([1, 2, 3]), c: Set([1, 2, 3]), }); const additions = Map({ a: Map({ y: 50, z: 100 }), b: List([4, 5, 6]), c: Set([4, 5, 6]), }); expect(initial.mergeDeep(additions)).toEqual( Map({ a: Map({ x: 10, y: 50, z: 100 }), b: List([1, 2, 3, 4, 5, 6]), c: Set([1, 2, 3, 4, 5, 6]), }) ); }); it('merges map entries with new values', () => { const initial = Map({ a: List([1]) }); // Note: merge and mergeDeep do not deeply coerce values, they only merge // with what's there prior. expect(initial.merge({ b: [2] } as any)).toEqual( Map({ a: List([1]), b: [2] }) ); expect(initial.mergeDeep({ b: [2] } as any)).toEqual( fromJS(Map({ a: List([1]), b: [2] })) ); }); it('maintains JS values inside immutable collections', () => { const m1 = fromJS({ a: { b: { imm: 'map' } } }) as Map<string, any>; const m2 = m1.mergeDeep(Map({ a: Map({ b: { plain: 'obj' } }) })); expect(m1.getIn(['a', 'b'])).toEqual(Map([['imm', 'map']])); // However mergeDeep will merge that value into the inner Map expect(m2.getIn(['a', 'b'])).toEqual(Map({ imm: 'map', plain: 'obj' })); }); it('merges plain Objects', () => { expect(merge({ x: 1, y: 1 }, { y: 2, z: 2 }, Map({ z: 3, q: 3 }))).toEqual({ x: 1, y: 2, z: 3, q: 3, }); }); it('merges plain Arrays', () => { expect(merge([1, 2], [3, 4], List([5, 6]))).toEqual([1, 2, 3, 4, 5, 6]); }); it('merging plain Array returns self after no-op', () => { const a = [1, 2, 3]; expect(merge(a, [], [])).toBe(a); }); it('merges records with a size property set to 0', () => { const Sizable = Record({ size: 0 }); expect(Sizable().merge({ size: 123 }).size).toBe(123); }); it('mergeDeep merges partial conflicts', () => { const a = fromJS({ ch: [ { code: 8, }, ], banana: 'good', }) as Map<unknown, unknown>; const b = fromJS({ ch: { code: 8, }, apple: 'anti-doctor', }); expect( a.mergeDeep(b).equals( fromJS({ ch: { code: 8, }, apple: 'anti-doctor', banana: 'good', }) ) ).toBe(true); }); const map = { type: 'Map', value: Map({ b: 5, c: 9 }) }; const object = { type: 'object', value: { b: 7, d: 12 } }; const RecordFactory = Record({ a: 1, b: 2 }); const record = { type: 'Record', value: RecordFactory({ b: 3 }) }; const list = { type: 'List', value: List(['5']) }; const array = { type: 'array', value: ['9'] }; const set = { type: 'Set', value: Set('3') }; const incompatibleTypes = [ [map, list], [map, array], [map, set], [object, list], [object, array], [object, set], [record, list], [record, array], [record, set], [list, set], ]; for (const [ { type: type1, value: value1 }, { type: type2, value: value2 }, ] of incompatibleTypes) { it(`mergeDeep and Map#mergeDeep replaces ${type1} and ${type2} with each other`, () => { const aObject = { a: value1 }; const bObject = { a: value2 }; expect(mergeDeep(aObject, bObject)).toEqual(bObject); expect(mergeDeep(bObject, aObject)).toEqual(aObject); const aMap = Map({ a: value1 }) as Map<unknown, unknown>; const bMap = Map({ a: value2 }) as Map<unknown, unknown>; expect(aMap.mergeDeep(bMap).equals(bMap)).toBe(true); expect(bMap.mergeDeep(aMap).equals(aMap)).toBe(true); }); } const compatibleTypesAndResult = [ [map, object, Map({ b: 7, c: 9, d: 12 })], [map, record, Map({ a: 1, b: 3, c: 9 })], [object, map, { b: 5, c: 9, d: 12 }], [object, record, { a: 1, b: 3, d: 12 }], [record, map, RecordFactory({ b: 5 })], [record, object, RecordFactory({ b: 7 })], [list, array, List(['5', '9'])], [array, list, ['9', '5']], [map, { type: 'Map', value: Map({ b: 7 }) }, Map({ b: 7, c: 9 })], [object, { type: 'object', value: { d: 3 } }, { b: 7, d: 3 }], [ record, { type: 'Record', value: RecordFactory({ a: 3 }) }, RecordFactory({ a: 3, b: 2 }), ], [list, { type: 'List', value: List(['12']) }, List(['5', '12'])], [array, { type: 'array', value: ['3'] }, ['9', '3']], [set, { type: 'Set', value: Set(['3', '5']) }, Set(['3', '5'])], ] as const; for (const [ { type: type1, value: value1 }, { type: type2, value: value2 }, result, ] of compatibleTypesAndResult) { it(`mergeDeep and Map#mergeDeep merges ${type1} and ${type2}`, () => { const aObject = { a: value1 }; const bObject = { a: value2 }; expect(mergeDeep(aObject, bObject)).toEqual({ a: result }); const aMap = Map({ a: value1 }) as Map<unknown, unknown>; const bMap = Map({ a: value2 }); expect(aMap.mergeDeep(bMap)).toEqual(Map({ a: result })); }); } it('Map#mergeDeep replaces nested List with Map and Map with List', () => { const a = Map({ a: List([Map({ x: 1 })]) }) as Map<unknown, unknown>; const b = Map({ a: Map([[0, Map({ y: 2 })]]) }) as Map<unknown, unknown>; expect(a.mergeDeep(b).equals(b)).toBe(true); expect(b.mergeDeep(a).equals(a)).toBe(true); }); it('functional mergeDeep replaces nested array with Map', () => { const a = { a: [{ x: 1 }] }; const b = Map({ a: Map([[0, Map({ y: 2 })]]) }); expect(mergeDeep(a, b)).toEqual({ a: Map([[0, Map({ y: 2 })]]) }); }); });
the_stack
import * as coreClient from "@azure/core-client"; /** Result of the request to list data exports. */ export interface DataExportListResult { /** List of data export instances within a workspace.. */ value?: DataExport[]; } /** Common fields that are returned in the response for all Azure Resource Manager resources */ export interface Resource { /** * Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the resource * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; } /** Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). */ export interface ErrorResponse { /** The error object. */ error?: ErrorDetail; } /** The error detail. */ export interface ErrorDetail { /** * The error code. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly code?: string; /** * The error message. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** * The error target. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly target?: string; /** * The error details. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly details?: ErrorDetail[]; /** * The error additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly additionalInfo?: ErrorAdditionalInfo[]; } /** The resource management error additional info. */ export interface ErrorAdditionalInfo { /** * The additional info type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly info?: Record<string, unknown>; } /** The list data source by workspace operation response. */ export interface DataSourceListResult { /** A list of datasources. */ value?: DataSource[]; /** The link (url) to the next page of datasources. */ nextLink?: string; } /** Intelligence Pack containing a string name and boolean indicating if it's enabled. */ export interface IntelligencePack { /** The name of the intelligence pack. */ name?: string; /** The enabled boolean for the intelligence pack. */ enabled?: boolean; /** The display name of the intelligence pack. */ displayName?: string; } /** The list linked service operation response. */ export interface LinkedServiceListResult { /** The list of linked service instances */ value?: LinkedService[]; } /** The list linked storage accounts service operation response. */ export interface LinkedStorageAccountsListResult { /** A list of linked storage accounts instances. */ value?: LinkedStorageAccountsResource[]; } /** The list workspace management groups operation response. */ export interface WorkspaceListManagementGroupsResult { /** Gets or sets a list of management groups attached to the workspace. */ value?: ManagementGroup[]; } /** A management group that is connected to a workspace */ export interface ManagementGroup { /** The number of servers connected to the management group. */ serverCount?: number; /** Gets or sets a value indicating whether the management group is a gateway. */ isGateway?: boolean; /** The name of the management group. */ name?: string; /** The unique ID of the management group. */ id?: string; /** The datetime that the management group was created. */ created?: Date; /** The last datetime that the management group received data. */ dataReceived?: Date; /** The version of System Center that is managing the management group. */ version?: string; /** The SKU of System Center that is managing the management group. */ sku?: string; } /** The status of operation. */ export interface OperationStatus { /** The operation Id. */ id?: string; /** The operation name. */ name?: string; /** The start time of the operation. */ startTime?: string; /** The end time of the operation. */ endTime?: string; /** The status of the operation. */ status?: string; /** The error detail of the operation if any. */ error?: ErrorResponse; } /** The shared keys for a workspace. */ export interface SharedKeys { /** The primary shared key of a workspace. */ primarySharedKey?: string; /** The secondary shared key of a workspace. */ secondarySharedKey?: string; } /** The list workspace usages operation response. */ export interface WorkspaceListUsagesResult { /** Gets or sets a list of usage metrics for a workspace. */ value?: UsageMetric[]; } /** A metric describing the usage of a resource. */ export interface UsageMetric { /** The name of the metric. */ name?: MetricName; /** The units used for the metric. */ unit?: string; /** The current value of the metric. */ currentValue?: number; /** The quota limit for the metric. */ limit?: number; /** The time that the metric's value will reset. */ nextResetTime?: Date; /** The quota period that determines the length of time between value resets. */ quotaPeriod?: string; } /** The name of a metric. */ export interface MetricName { /** The system name of the metric. */ value?: string; /** The localized name of the metric. */ localizedValue?: string; } /** Describes a storage account connection. */ export interface StorageAccount { /** The Azure Resource Manager ID of the storage account resource. */ id: string; /** The storage account key. */ key: string; } /** The status of the storage insight. */ export interface StorageInsightStatus { /** The state of the storage insight connection to the workspace */ state: StorageInsightState; /** Description of the state of the storage insight. */ description?: string; } /** The list storage insights operation response. */ export interface StorageInsightListResult { /** A list of storage insight items. */ value?: StorageInsight[]; /** The link (url) to the next page of results. */ odataNextLink?: string; } /** A tag of a saved search. */ export interface Tag { /** The tag name. */ name: string; /** The tag value. */ value: string; } /** The saved search list operation response. */ export interface SavedSearchesListResult { /** The array of result values. */ value?: SavedSearch[]; } /** Service Tier details. */ export interface AvailableServiceTier { /** * The name of the Service Tier. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly serviceTier?: SkuNameEnum; /** * True if the Service Tier is enabled for the workspace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly enabled?: boolean; /** * The minimum retention for the Service Tier, in days. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly minimumRetention?: number; /** * The maximum retention for the Service Tier, in days. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maximumRetention?: number; /** * The default retention for the Service Tier, in days. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly defaultRetention?: number; /** * The capacity reservation level in GB per day. Returned for the Capacity Reservation Service Tier. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly capacityReservationLevel?: number; /** * Time when the sku was last updated for the workspace. Returned for the Capacity Reservation Service Tier. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastSkuUpdate?: string; } /** The get schema operation response. */ export interface SearchGetSchemaResponse { /** The metadata from search results. */ metadata?: SearchMetadata; /** The array of result values. */ value?: SearchSchemaValue[]; } /** Metadata for search results. */ export interface SearchMetadata { /** The request id of the search. */ searchId?: string; /** The search result type. */ resultType?: string; /** The total number of search results. */ total?: number; /** The number of top search results. */ top?: number; /** The id of the search results request. */ id?: string; /** The core summaries. */ coreSummaries?: CoreSummary[]; /** The status of the search results. */ status?: string; /** The start time for the search. */ startTime?: Date; /** The time of last update. */ lastUpdated?: Date; /** The ETag of the search results. */ eTag?: string; /** How the results are sorted. */ sort?: SearchSort[]; /** The request time. */ requestTime?: number; /** The aggregated value field. */ aggregatedValueField?: string; /** The aggregated grouping fields. */ aggregatedGroupingFields?: string; /** The sum of all aggregates returned in the result set. */ sum?: number; /** The max of all aggregates returned in the result set. */ max?: number; /** The schema. */ schema?: SearchMetadataSchema; } /** The core summary of a search. */ export interface CoreSummary { /** The status of a core summary. */ status?: string; /** The number of documents of a core summary. */ numberOfDocuments: number; } /** The sort parameters for search. */ export interface SearchSort { /** The name of the field the search query is sorted on. */ name?: string; /** The sort order of the search. */ order?: SearchSortEnum; } /** Schema metadata for search. */ export interface SearchMetadataSchema { /** The name of the metadata schema. */ name?: string; /** The version of the metadata schema. */ version?: number; } /** Value object for schema results. */ export interface SearchSchemaValue { /** The name of the schema. */ name?: string; /** The display name of the schema. */ displayName?: string; /** The type. */ type?: string; /** The boolean that indicates the field is searchable as free text. */ indexed: boolean; /** The boolean that indicates whether or not the field is stored. */ stored: boolean; /** The boolean that indicates whether or not the field is a facet. */ facet: boolean; /** The array of workflows containing the field. */ ownerType?: string[]; } /** Describes the body of a purge request for an App Insights Workspace */ export interface WorkspacePurgeBody { /** Table from which to purge data. */ table: string; /** The set of columns and filters (queries) to run over them to purge the resulting data. */ filters: WorkspacePurgeBodyFilters[]; } /** User-defined filters to return data which will be purged from the table. */ export interface WorkspacePurgeBodyFilters { /** The column of the table over which the given query should run */ column?: string; /** A query operator to evaluate over the provided column and value(s). Supported operators are ==, =~, in, in~, >, >=, <, <=, between, and have the same behavior as they would in a KQL query. */ operator?: string; /** the value for the operator to function over. This can be a number (e.g., > 100), a string (timestamp >= '2017-09-01') or array of values. */ value?: any; /** When filtering over custom dimensions, this key will be used as the name of the custom dimension. */ key?: string; } /** Response containing operationId for a specific purge action. */ export interface WorkspacePurgeResponse { /** Id to use when querying for status for a particular purge operation. */ operationId: string; } /** Response containing status for a specific purge operation. */ export interface WorkspacePurgeStatusResponse { /** Status of the operation represented by the requested Id. */ status: PurgeState; } /** Result of the request to list solution operations. */ export interface OperationListResult { /** List of solution operations supported by the OperationsManagement resource provider. */ value?: Operation[]; /** * URL to get the next set of operation list results if there are any. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Supported operation of OperationalInsights resource provider. */ export interface Operation { /** Operation name: {provider}/{resource}/{operation} */ name?: string; /** Display metadata associated with the operation. */ display?: OperationDisplay; } /** Display metadata associated with the operation. */ export interface OperationDisplay { /** Service provider: Microsoft OperationsManagement. */ provider?: string; /** Resource on which the operation is performed etc. */ resource?: string; /** Type of operation: get, read, delete, etc. */ operation?: string; /** Description of operation */ description?: string; } /** The list tables operation response. */ export interface TablesListResult { /** A list of data tables. */ value?: Table[]; } /** The list clusters operation response. */ export interface ClusterListResult { /** The link used to get the next page of recommendations. */ nextLink?: string; /** A list of Log Analytics clusters. */ value?: Cluster[]; } /** Identity for the resource. */ export interface Identity { /** * The principal ID of resource identity. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly principalId?: string; /** * The tenant ID of resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly tenantId?: string; /** Type of managed service identity. */ type: IdentityType; /** The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. */ userAssignedIdentities?: { [propertyName: string]: UserIdentityProperties }; } /** User assigned identity properties. */ export interface UserIdentityProperties { /** * The principal id of user assigned identity. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly principalId?: string; /** * The client id of user assigned identity. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly clientId?: string; } /** The cluster sku definition. */ export interface ClusterSku { /** The capacity value */ capacity?: Capacity; /** The name of the SKU. */ name?: ClusterSkuNameEnum; } /** The key vault properties. */ export interface KeyVaultProperties { /** The Key Vault uri which holds they key associated with the Log Analytics cluster. */ keyVaultUri?: string; /** The name of the key associated with the Log Analytics cluster. */ keyName?: string; /** The version of the key associated with the Log Analytics cluster. */ keyVersion?: string; /** Selected key minimum required size. */ keyRsaSize?: number; } /** The list of Log Analytics workspaces associated with the cluster. */ export interface AssociatedWorkspace { /** * The id of the assigned workspace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly workspaceId?: string; /** * The name id the assigned workspace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly workspaceName?: string; /** * The ResourceId id the assigned workspace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceId?: string; /** * The time of workspace association. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly associateDate?: string; } /** The Capacity Reservation properties. */ export interface CapacityReservationProperties { /** * The last time Sku was updated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastSkuUpdate?: string; /** * Minimum CapacityReservation value in GB. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly minCapacity?: number; } /** The top level Log Analytics cluster resource container. */ export interface ClusterPatch { /** The identity of the resource. */ identity?: Identity; /** The sku properties. */ sku?: ClusterSku; /** Resource tags. */ tags?: { [propertyName: string]: string }; /** The associated key properties. */ keyVaultProperties?: KeyVaultProperties; /** The cluster's billing type. */ billingType?: BillingType; } /** The list workspaces operation response. */ export interface WorkspaceListResult { /** A list of workspaces. */ value?: Workspace[]; } /** The SKU (tier) of a workspace. */ export interface WorkspaceSku { /** The name of the SKU. */ name: WorkspaceSkuNameEnum; /** The capacity reservation level in GB for this workspace, when CapacityReservation sku is selected. */ capacityReservationLevel?: CapacityReservationLevel; /** * The last time when the sku was updated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastSkuUpdate?: string; } /** The daily volume cap for ingestion. */ export interface WorkspaceCapping { /** The workspace daily quota for ingestion. */ dailyQuotaGb?: number; /** * The time when the quota will be rest. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly quotaNextResetTime?: string; /** * The status of data ingestion for this workspace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly dataIngestionStatus?: DataIngestionStatus; } /** The private link scope resource reference. */ export interface PrivateLinkScopedResource { /** The full resource Id of the private link scope resource. */ resourceId?: string; /** The private link scope unique Identifier. */ scopeId?: string; } /** Workspace features. */ export interface WorkspaceFeatures { /** Describes unknown properties. The value of an unknown property can be of "any" type. */ [property: string]: any; /** Flag that indicate if data should be exported. */ enableDataExport?: boolean; /** Flag that describes if we want to remove the data after 30 days. */ immediatePurgeDataOn30Days?: boolean; /** Flag that indicate which permission to use - resource or workspace or both. */ enableLogAccessUsingOnlyResourcePermissions?: boolean; /** Dedicated LA cluster resourceId that is linked to the workspaces. */ clusterResourceId?: string; /** Disable Non-AAD based Auth. */ disableLocalAuth?: boolean; } /** DataSource filter. Right now, only filter by kind is supported. */ export interface DataSourceFilter { /** The kind of the DataSource. */ kind?: DataSourceKind; } /** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */ export type ProxyResource = Resource & {}; /** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ export type TrackedResource = Resource & { /** Resource tags. */ tags?: { [propertyName: string]: string }; /** The geo-location where the resource lives */ location: string; }; /** The resource model definition for an Azure Resource Manager resource with an etag. */ export type AzureEntityResource = Resource & { /** * Resource Etag. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly etag?: string; }; /** The top level data export resource container. */ export type DataExport = ProxyResource & { /** The data export rule ID. */ dataExportId?: string; /** An array of tables to export, for example: [“Heartbeat, SecurityEvent”]. */ tableNames?: string[]; /** Active when enabled. */ enable?: boolean; /** The latest data export rule modification time. */ createdDate?: string; /** Date and time when the export was last modified. */ lastModifiedDate?: string; /** The destination resource ID. This can be copied from the Properties entry of the destination resource in Azure. */ resourceId?: string; /** * The type of the destination resource * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly typePropertiesDestinationType?: Type; /** Optional. Allows to define an Event Hub name. Not applicable when destination is Storage Account. */ eventHubName?: string; }; /** Datasources under OMS Workspace. */ export type DataSource = ProxyResource & { /** The data source properties in raw json format, each kind of data source have it's own schema. */ properties: Record<string, unknown>; /** The ETag of the data source. */ etag?: string; /** The kind of the DataSource. */ kind: DataSourceKind; /** Resource tags. */ tags?: { [propertyName: string]: string }; }; /** The top level Linked service resource container. */ export type LinkedService = ProxyResource & { /** Resource tags. */ tags?: { [propertyName: string]: string }; /** The resource id of the resource that will be linked to the workspace. This should be used for linking resources which require read access */ resourceId?: string; /** The resource id of the resource that will be linked to the workspace. This should be used for linking resources which require write access */ writeAccessResourceId?: string; /** The provisioning state of the linked service. */ provisioningState?: LinkedServiceEntityStatus; }; /** Linked storage accounts top level resource container. */ export type LinkedStorageAccountsResource = ProxyResource & { /** * Linked storage accounts type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly dataSourceType?: DataSourceType; /** Linked storage accounts resources ids. */ storageAccountIds?: string[]; }; /** The top level storage insight resource container. */ export type StorageInsight = ProxyResource & { /** The ETag of the storage insight. */ eTag?: string; /** Resource tags. */ tags?: { [propertyName: string]: string }; /** The names of the blob containers that the workspace should read */ containers?: string[]; /** The names of the Azure tables that the workspace should read */ tables?: string[]; /** The storage account connection details */ storageAccount?: StorageAccount; /** * The status of the storage insight * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly status?: StorageInsightStatus; }; /** Value object for saved search results. */ export type SavedSearch = ProxyResource & { /** The ETag of the saved search. To override an existing saved search, use "*" or specify the current Etag */ etag?: string; /** The category of the saved search. This helps the user to find a saved search faster. */ category: string; /** Saved search display name. */ displayName: string; /** The query expression for the saved search. */ query: string; /** The function alias if query serves as a function. */ functionAlias?: string; /** The optional function parameters if query serves as a function. Value should be in the following format: 'param-name1:type1 = default_value1, param-name2:type2 = default_value2'. For more examples and proper syntax please refer to https://docs.microsoft.com/en-us/azure/kusto/query/functions/user-defined-functions. */ functionParameters?: string; /** The version number of the query language. The current version is 2 and is the default. */ version?: number; /** The tags attached to the saved search. */ tags?: Tag[]; }; /** Workspace data table definition. */ export type Table = ProxyResource & { /** The data table data retention in days, between 7 and 730. Setting this property to null will default to the workspace retention. */ retentionInDays?: number; /** * Specifies if IsTroubleshootingEnabled property can be set for this table. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly isTroubleshootingAllowed?: boolean; /** Enable or disable troubleshoot for this table. */ isTroubleshootEnabled?: boolean; /** * Last time when troubleshooting was set for this table. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastTroubleshootDate?: string; }; /** The top level Log Analytics cluster resource container. */ export type Cluster = TrackedResource & { /** The identity of the resource. */ identity?: Identity; /** The sku properties. */ sku?: ClusterSku; /** * The ID associated with the cluster. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly clusterId?: string; /** * The provisioning state of the cluster. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: ClusterEntityStatus; /** Configures whether cluster will use double encryption. This Property can not be modified after cluster creation. Default value is 'true' */ isDoubleEncryptionEnabled?: boolean; /** Sets whether the cluster will support availability zones. This can be set as true only in regions where Azure Data Explorer support Availability Zones. This Property can not be modified after cluster creation. Default value is 'true' if region supports Availability Zones. */ isAvailabilityZonesEnabled?: boolean; /** The cluster's billing type. */ billingType?: BillingType; /** The associated key properties. */ keyVaultProperties?: KeyVaultProperties; /** * The last time the cluster was updated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastModifiedDate?: string; /** * The cluster creation time * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdDate?: string; /** The list of Log Analytics workspaces associated with the cluster */ associatedWorkspaces?: AssociatedWorkspace[]; /** Additional properties for capacity reservation */ capacityReservationProperties?: CapacityReservationProperties; }; /** The top level Workspace resource container. */ export type Workspace = TrackedResource & { /** The ETag of the workspace. */ eTag?: string; /** The provisioning state of the workspace. */ provisioningState?: WorkspaceEntityStatus; /** * This is a read-only property. Represents the ID associated with the workspace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly customerId?: string; /** The SKU of the workspace. */ sku?: WorkspaceSku; /** The workspace data retention in days. Allowed values are per pricing plan. See pricing tiers documentation for details. */ retentionInDays?: number; /** The daily volume cap for ingestion. */ workspaceCapping?: WorkspaceCapping; /** * Workspace creation date. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdDate?: string; /** * Workspace modification date. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly modifiedDate?: string; /** The network access type for accessing Log Analytics ingestion. */ publicNetworkAccessForIngestion?: PublicNetworkAccessType; /** The network access type for accessing Log Analytics query. */ publicNetworkAccessForQuery?: PublicNetworkAccessType; /** Indicates whether customer managed storage is mandatory for query management. */ forceCmkForQuery?: boolean; /** * List of linked private link scope resources. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly privateLinkScopedResources?: PrivateLinkScopedResource[]; /** Workspace features. */ features?: WorkspaceFeatures; }; /** The top level Workspace resource container. */ export type WorkspacePatch = AzureEntityResource & { /** Resource tags. Optional. */ tags?: { [propertyName: string]: string }; /** The provisioning state of the workspace. */ provisioningState?: WorkspaceEntityStatus; /** * This is a read-only property. Represents the ID associated with the workspace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly customerId?: string; /** The SKU of the workspace. */ sku?: WorkspaceSku; /** The workspace data retention in days. Allowed values are per pricing plan. See pricing tiers documentation for details. */ retentionInDays?: number; /** The daily volume cap for ingestion. */ workspaceCapping?: WorkspaceCapping; /** * Workspace creation date. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdDate?: string; /** * Workspace modification date. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly modifiedDate?: string; /** The network access type for accessing Log Analytics ingestion. */ publicNetworkAccessForIngestion?: PublicNetworkAccessType; /** The network access type for accessing Log Analytics query. */ publicNetworkAccessForQuery?: PublicNetworkAccessType; /** Indicates whether customer managed storage is mandatory for query management. */ forceCmkForQuery?: boolean; /** * List of linked private link scope resources. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly privateLinkScopedResources?: PrivateLinkScopedResource[]; /** Workspace features. */ features?: WorkspaceFeatures; }; /** Defines headers for WorkspacePurge_purge operation. */ export interface WorkspacePurgePurgeHeaders { /** The location from which to request the operation status. */ xMsStatusLocation?: string; } /** Known values of {@link Type} that the service accepts. */ export enum KnownType { StorageAccount = "StorageAccount", EventHub = "EventHub" } /** * Defines values for Type. \ * {@link KnownType} can be used interchangeably with Type, * this enum contains the known values that the service supports. * ### Known values supported by the service * **StorageAccount** \ * **EventHub** */ export type Type = string; /** Known values of {@link DataSourceKind} that the service accepts. */ export enum KnownDataSourceKind { WindowsEvent = "WindowsEvent", WindowsPerformanceCounter = "WindowsPerformanceCounter", IISLogs = "IISLogs", LinuxSyslog = "LinuxSyslog", LinuxSyslogCollection = "LinuxSyslogCollection", LinuxPerformanceObject = "LinuxPerformanceObject", LinuxPerformanceCollection = "LinuxPerformanceCollection", CustomLog = "CustomLog", CustomLogCollection = "CustomLogCollection", AzureAuditLog = "AzureAuditLog", AzureActivityLog = "AzureActivityLog", GenericDataSource = "GenericDataSource", ChangeTrackingCustomPath = "ChangeTrackingCustomPath", ChangeTrackingPath = "ChangeTrackingPath", ChangeTrackingServices = "ChangeTrackingServices", ChangeTrackingDataTypeConfiguration = "ChangeTrackingDataTypeConfiguration", ChangeTrackingDefaultRegistry = "ChangeTrackingDefaultRegistry", ChangeTrackingRegistry = "ChangeTrackingRegistry", ChangeTrackingLinuxPath = "ChangeTrackingLinuxPath", LinuxChangeTrackingPath = "LinuxChangeTrackingPath", ChangeTrackingContentLocation = "ChangeTrackingContentLocation", WindowsTelemetry = "WindowsTelemetry", Office365 = "Office365", SecurityWindowsBaselineConfiguration = "SecurityWindowsBaselineConfiguration", SecurityCenterSecurityWindowsBaselineConfiguration = "SecurityCenterSecurityWindowsBaselineConfiguration", SecurityEventCollectionConfiguration = "SecurityEventCollectionConfiguration", SecurityInsightsSecurityEventCollectionConfiguration = "SecurityInsightsSecurityEventCollectionConfiguration", ImportComputerGroup = "ImportComputerGroup", NetworkMonitoring = "NetworkMonitoring", Itsm = "Itsm", DnsAnalytics = "DnsAnalytics", ApplicationInsights = "ApplicationInsights", SqlDataClassification = "SqlDataClassification" } /** * Defines values for DataSourceKind. \ * {@link KnownDataSourceKind} can be used interchangeably with DataSourceKind, * this enum contains the known values that the service supports. * ### Known values supported by the service * **WindowsEvent** \ * **WindowsPerformanceCounter** \ * **IISLogs** \ * **LinuxSyslog** \ * **LinuxSyslogCollection** \ * **LinuxPerformanceObject** \ * **LinuxPerformanceCollection** \ * **CustomLog** \ * **CustomLogCollection** \ * **AzureAuditLog** \ * **AzureActivityLog** \ * **GenericDataSource** \ * **ChangeTrackingCustomPath** \ * **ChangeTrackingPath** \ * **ChangeTrackingServices** \ * **ChangeTrackingDataTypeConfiguration** \ * **ChangeTrackingDefaultRegistry** \ * **ChangeTrackingRegistry** \ * **ChangeTrackingLinuxPath** \ * **LinuxChangeTrackingPath** \ * **ChangeTrackingContentLocation** \ * **WindowsTelemetry** \ * **Office365** \ * **SecurityWindowsBaselineConfiguration** \ * **SecurityCenterSecurityWindowsBaselineConfiguration** \ * **SecurityEventCollectionConfiguration** \ * **SecurityInsightsSecurityEventCollectionConfiguration** \ * **ImportComputerGroup** \ * **NetworkMonitoring** \ * **Itsm** \ * **DnsAnalytics** \ * **ApplicationInsights** \ * **SqlDataClassification** */ export type DataSourceKind = string; /** Known values of {@link LinkedServiceEntityStatus} that the service accepts. */ export enum KnownLinkedServiceEntityStatus { Succeeded = "Succeeded", Deleting = "Deleting", ProvisioningAccount = "ProvisioningAccount", Updating = "Updating" } /** * Defines values for LinkedServiceEntityStatus. \ * {@link KnownLinkedServiceEntityStatus} can be used interchangeably with LinkedServiceEntityStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Succeeded** \ * **Deleting** \ * **ProvisioningAccount** \ * **Updating** */ export type LinkedServiceEntityStatus = string; /** Known values of {@link StorageInsightState} that the service accepts. */ export enum KnownStorageInsightState { OK = "OK", Error = "ERROR" } /** * Defines values for StorageInsightState. \ * {@link KnownStorageInsightState} can be used interchangeably with StorageInsightState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **OK** \ * **ERROR** */ export type StorageInsightState = string; /** Known values of {@link SkuNameEnum} that the service accepts. */ export enum KnownSkuNameEnum { Free = "Free", Standard = "Standard", Premium = "Premium", PerNode = "PerNode", PerGB2018 = "PerGB2018", Standalone = "Standalone", CapacityReservation = "CapacityReservation" } /** * Defines values for SkuNameEnum. \ * {@link KnownSkuNameEnum} can be used interchangeably with SkuNameEnum, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Free** \ * **Standard** \ * **Premium** \ * **PerNode** \ * **PerGB2018** \ * **Standalone** \ * **CapacityReservation** */ export type SkuNameEnum = string; /** Known values of {@link SearchSortEnum} that the service accepts. */ export enum KnownSearchSortEnum { Asc = "asc", Desc = "desc" } /** * Defines values for SearchSortEnum. \ * {@link KnownSearchSortEnum} can be used interchangeably with SearchSortEnum, * this enum contains the known values that the service supports. * ### Known values supported by the service * **asc** \ * **desc** */ export type SearchSortEnum = string; /** Known values of {@link PurgeState} that the service accepts. */ export enum KnownPurgeState { Pending = "pending", Completed = "completed" } /** * Defines values for PurgeState. \ * {@link KnownPurgeState} can be used interchangeably with PurgeState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **pending** \ * **completed** */ export type PurgeState = string; /** Known values of {@link ClusterSkuNameEnum} that the service accepts. */ export enum KnownClusterSkuNameEnum { CapacityReservation = "CapacityReservation" } /** * Defines values for ClusterSkuNameEnum. \ * {@link KnownClusterSkuNameEnum} can be used interchangeably with ClusterSkuNameEnum, * this enum contains the known values that the service supports. * ### Known values supported by the service * **CapacityReservation** */ export type ClusterSkuNameEnum = string; /** Known values of {@link ClusterEntityStatus} that the service accepts. */ export enum KnownClusterEntityStatus { Creating = "Creating", Succeeded = "Succeeded", Failed = "Failed", Canceled = "Canceled", Deleting = "Deleting", ProvisioningAccount = "ProvisioningAccount", Updating = "Updating" } /** * Defines values for ClusterEntityStatus. \ * {@link KnownClusterEntityStatus} can be used interchangeably with ClusterEntityStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Creating** \ * **Succeeded** \ * **Failed** \ * **Canceled** \ * **Deleting** \ * **ProvisioningAccount** \ * **Updating** */ export type ClusterEntityStatus = string; /** Known values of {@link BillingType} that the service accepts. */ export enum KnownBillingType { Cluster = "Cluster", Workspaces = "Workspaces" } /** * Defines values for BillingType. \ * {@link KnownBillingType} can be used interchangeably with BillingType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Cluster** \ * **Workspaces** */ export type BillingType = string; /** Known values of {@link WorkspaceEntityStatus} that the service accepts. */ export enum KnownWorkspaceEntityStatus { Creating = "Creating", Succeeded = "Succeeded", Failed = "Failed", Canceled = "Canceled", Deleting = "Deleting", ProvisioningAccount = "ProvisioningAccount", Updating = "Updating" } /** * Defines values for WorkspaceEntityStatus. \ * {@link KnownWorkspaceEntityStatus} can be used interchangeably with WorkspaceEntityStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Creating** \ * **Succeeded** \ * **Failed** \ * **Canceled** \ * **Deleting** \ * **ProvisioningAccount** \ * **Updating** */ export type WorkspaceEntityStatus = string; /** Known values of {@link WorkspaceSkuNameEnum} that the service accepts. */ export enum KnownWorkspaceSkuNameEnum { Free = "Free", Standard = "Standard", Premium = "Premium", PerNode = "PerNode", PerGB2018 = "PerGB2018", Standalone = "Standalone", CapacityReservation = "CapacityReservation", LACluster = "LACluster" } /** * Defines values for WorkspaceSkuNameEnum. \ * {@link KnownWorkspaceSkuNameEnum} can be used interchangeably with WorkspaceSkuNameEnum, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Free** \ * **Standard** \ * **Premium** \ * **PerNode** \ * **PerGB2018** \ * **Standalone** \ * **CapacityReservation** \ * **LACluster** */ export type WorkspaceSkuNameEnum = string; /** Known values of {@link DataIngestionStatus} that the service accepts. */ export enum KnownDataIngestionStatus { /** Ingestion enabled following daily cap quota reset, or subscription enablement. */ RespectQuota = "RespectQuota", /** Ingestion started following service setting change. */ ForceOn = "ForceOn", /** Ingestion stopped following service setting change. */ ForceOff = "ForceOff", /** Reached daily cap quota, ingestion stopped. */ OverQuota = "OverQuota", /** Ingestion stopped following suspended subscription. */ SubscriptionSuspended = "SubscriptionSuspended", /** 80% of daily cap quota reached. */ ApproachingQuota = "ApproachingQuota" } /** * Defines values for DataIngestionStatus. \ * {@link KnownDataIngestionStatus} can be used interchangeably with DataIngestionStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **RespectQuota**: Ingestion enabled following daily cap quota reset, or subscription enablement. \ * **ForceOn**: Ingestion started following service setting change. \ * **ForceOff**: Ingestion stopped following service setting change. \ * **OverQuota**: Reached daily cap quota, ingestion stopped. \ * **SubscriptionSuspended**: Ingestion stopped following suspended subscription. \ * **ApproachingQuota**: 80% of daily cap quota reached. */ export type DataIngestionStatus = string; /** Known values of {@link PublicNetworkAccessType} that the service accepts. */ export enum KnownPublicNetworkAccessType { /** Enables connectivity to Log Analytics through public DNS. */ Enabled = "Enabled", /** Disables public connectivity to Log Analytics through public DNS. */ Disabled = "Disabled" } /** * Defines values for PublicNetworkAccessType. \ * {@link KnownPublicNetworkAccessType} can be used interchangeably with PublicNetworkAccessType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled**: Enables connectivity to Log Analytics through public DNS. \ * **Disabled**: Disables public connectivity to Log Analytics through public DNS. */ export type PublicNetworkAccessType = string; /** Defines values for DataSourceType. */ export type DataSourceType = "CustomLogs" | "AzureWatson" | "Query" | "Alerts"; /** Defines values for IdentityType. */ export type IdentityType = "SystemAssigned" | "UserAssigned" | "None"; /** Defines values for Capacity. */ export type Capacity = 500 | 1000 | 2000 | 5000; /** Defines values for CapacityReservationLevel. */ export type CapacityReservationLevel = | 100 | 200 | 300 | 400 | 500 | 1000 | 2000 | 5000; /** Optional parameters. */ export interface DataExportsListByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspace operation. */ export type DataExportsListByWorkspaceResponse = DataExportListResult; /** Optional parameters. */ export interface DataExportsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type DataExportsCreateOrUpdateResponse = DataExport; /** Optional parameters. */ export interface DataExportsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type DataExportsGetResponse = DataExport; /** Optional parameters. */ export interface DataExportsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DataSourcesCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type DataSourcesCreateOrUpdateResponse = DataSource; /** Optional parameters. */ export interface DataSourcesDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DataSourcesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type DataSourcesGetResponse = DataSource; /** Optional parameters. */ export interface DataSourcesListByWorkspaceOptionalParams extends coreClient.OperationOptions { /** Starting point of the collection of data source instances. */ skiptoken?: string; } /** Contains response data for the listByWorkspace operation. */ export type DataSourcesListByWorkspaceResponse = DataSourceListResult; /** Optional parameters. */ export interface DataSourcesListByWorkspaceNextOptionalParams extends coreClient.OperationOptions { /** Starting point of the collection of data source instances. */ skiptoken?: string; } /** Contains response data for the listByWorkspaceNext operation. */ export type DataSourcesListByWorkspaceNextResponse = DataSourceListResult; /** Optional parameters. */ export interface IntelligencePacksDisableOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface IntelligencePacksEnableOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface IntelligencePacksListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type IntelligencePacksListResponse = IntelligencePack[]; /** Optional parameters. */ export interface LinkedServicesCreateOrUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the createOrUpdate operation. */ export type LinkedServicesCreateOrUpdateResponse = LinkedService; /** Optional parameters. */ export interface LinkedServicesDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the delete operation. */ export type LinkedServicesDeleteResponse = LinkedService; /** Optional parameters. */ export interface LinkedServicesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type LinkedServicesGetResponse = LinkedService; /** Optional parameters. */ export interface LinkedServicesListByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspace operation. */ export type LinkedServicesListByWorkspaceResponse = LinkedServiceListResult; /** Optional parameters. */ export interface LinkedStorageAccountsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type LinkedStorageAccountsCreateOrUpdateResponse = LinkedStorageAccountsResource; /** Optional parameters. */ export interface LinkedStorageAccountsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface LinkedStorageAccountsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type LinkedStorageAccountsGetResponse = LinkedStorageAccountsResource; /** Optional parameters. */ export interface LinkedStorageAccountsListByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspace operation. */ export type LinkedStorageAccountsListByWorkspaceResponse = LinkedStorageAccountsListResult; /** Optional parameters. */ export interface ManagementGroupsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type ManagementGroupsListResponse = WorkspaceListManagementGroupsResult; /** Optional parameters. */ export interface OperationStatusesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type OperationStatusesGetResponse = OperationStatus; /** Optional parameters. */ export interface SharedKeysGetSharedKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getSharedKeys operation. */ export type SharedKeysGetSharedKeysResponse = SharedKeys; /** Optional parameters. */ export interface SharedKeysRegenerateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the regenerate operation. */ export type SharedKeysRegenerateResponse = SharedKeys; /** Optional parameters. */ export interface UsagesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type UsagesListResponse = WorkspaceListUsagesResult; /** Optional parameters. */ export interface StorageInsightConfigsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type StorageInsightConfigsCreateOrUpdateResponse = StorageInsight; /** Optional parameters. */ export interface StorageInsightConfigsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type StorageInsightConfigsGetResponse = StorageInsight; /** Optional parameters. */ export interface StorageInsightConfigsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface StorageInsightConfigsListByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspace operation. */ export type StorageInsightConfigsListByWorkspaceResponse = StorageInsightListResult; /** Optional parameters. */ export interface StorageInsightConfigsListByWorkspaceNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspaceNext operation. */ export type StorageInsightConfigsListByWorkspaceNextResponse = StorageInsightListResult; /** Optional parameters. */ export interface SavedSearchesDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface SavedSearchesCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type SavedSearchesCreateOrUpdateResponse = SavedSearch; /** Optional parameters. */ export interface SavedSearchesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type SavedSearchesGetResponse = SavedSearch; /** Optional parameters. */ export interface SavedSearchesListByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspace operation. */ export type SavedSearchesListByWorkspaceResponse = SavedSearchesListResult; /** Optional parameters. */ export interface AvailableServiceTiersListByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspace operation. */ export type AvailableServiceTiersListByWorkspaceResponse = AvailableServiceTier[]; /** Optional parameters. */ export interface GatewaysDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface SchemaGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type SchemaGetResponse = SearchGetSchemaResponse; /** Optional parameters. */ export interface WorkspacePurgePurgeOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the purge operation. */ export type WorkspacePurgePurgeResponse = WorkspacePurgePurgeHeaders & WorkspacePurgeResponse; /** Optional parameters. */ export interface WorkspacePurgeGetPurgeStatusOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getPurgeStatus operation. */ export type WorkspacePurgeGetPurgeStatusResponse = WorkspacePurgeStatusResponse; /** Optional parameters. */ export interface OperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult; /** Optional parameters. */ export interface OperationsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult; /** Optional parameters. */ export interface TablesListByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspace operation. */ export type TablesListByWorkspaceResponse = TablesListResult; /** Optional parameters. */ export interface TablesUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the update operation. */ export type TablesUpdateResponse = Table; /** Optional parameters. */ export interface TablesCreateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the create operation. */ export type TablesCreateResponse = Table; /** Optional parameters. */ export interface TablesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type TablesGetResponse = Table; /** Optional parameters. */ export interface ClustersListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type ClustersListByResourceGroupResponse = ClusterListResult; /** Optional parameters. */ export interface ClustersListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type ClustersListResponse = ClusterListResult; /** Optional parameters. */ export interface ClustersCreateOrUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the createOrUpdate operation. */ export type ClustersCreateOrUpdateResponse = Cluster; /** Optional parameters. */ export interface ClustersDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ClustersGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type ClustersGetResponse = Cluster; /** Optional parameters. */ export interface ClustersUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type ClustersUpdateResponse = Cluster; /** Optional parameters. */ export interface ClustersListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type ClustersListByResourceGroupNextResponse = ClusterListResult; /** Optional parameters. */ export interface ClustersListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type ClustersListNextResponse = ClusterListResult; /** Optional parameters. */ export interface WorkspacesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type WorkspacesListResponse = WorkspaceListResult; /** Optional parameters. */ export interface WorkspacesListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type WorkspacesListByResourceGroupResponse = WorkspaceListResult; /** Optional parameters. */ export interface WorkspacesCreateOrUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the createOrUpdate operation. */ export type WorkspacesCreateOrUpdateResponse = Workspace; /** Optional parameters. */ export interface WorkspacesDeleteOptionalParams extends coreClient.OperationOptions { /** Deletes the workspace without the recovery option. A workspace that was deleted with this flag cannot be recovered. */ force?: boolean; /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface WorkspacesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type WorkspacesGetResponse = Workspace; /** Optional parameters. */ export interface WorkspacesUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the update operation. */ export type WorkspacesUpdateResponse = Workspace; /** Optional parameters. */ export interface DeletedWorkspacesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type DeletedWorkspacesListResponse = WorkspaceListResult; /** Optional parameters. */ export interface DeletedWorkspacesListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type DeletedWorkspacesListByResourceGroupResponse = WorkspaceListResult; /** Optional parameters. */ export interface OperationalInsightsManagementClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { createStore, Store } from 'redux'; import { RSAA, isRSAA, validateRSAA, isValidRSAA, InvalidRSAA, InternalError, RequestError, ApiError, getJSON, createMiddleware, apiMiddleware, RSAAAction, RSAACall, RSAARequestTypeDescriptor, RSAASuccessTypeDescriptor, RSAAFailureTypeDescriptor, RSAARequestAction, RSAAResultAction, createAction, } from 'redux-api-middleware'; { // RSAA const passRSAA: typeof RSAA = '@@redux-api-middleware/RSAA'; const failRSAA: typeof RSAA = '@@redux-api-middleware/RSAA-fail'; // $ExpectError } { // isRSAA isRSAA({}); // $ExpectType boolean isRSAA(); // $ExpectError } { // validateRSAA validateRSAA({}); // $ExpectType string[] validateRSAA(); // $ExpectError } { // isValidRSAA isValidRSAA({}); // $ExpectType boolean isValidRSAA(); // $ExpectError } { // InvalidRSAA new InvalidRSAA([]); // $ExpectType InvalidRSAA new InvalidRSAA([]).message; // $ExpectType "Invalid RSAA" new InvalidRSAA([]).name; // $ExpectType "InvalidRSAA" new InvalidRSAA([]).validationErrors; // $ExpectType string[] new InvalidRSAA(['']); new InvalidRSAA(); // $ExpectError new InvalidRSAA([0]); // $ExpectError } { // InternalError new InternalError(''); // $ExpectType InternalError new InternalError('').name; // $ExpectType "InternalError" new InternalError(); // $ExpectError new InternalError(0); // $ExpectError } { // RequestError new RequestError(''); // $ExpectType RequestError new RequestError('').name; // $ExpectType "RequestError" new RequestError(); // $ExpectError new RequestError(0); // $ExpectError } { // ApiError new ApiError(200, 'OK', {}); // $ExpectType ApiError<{}> new ApiError(200, 'OK', {}).name; // $ExpectType "ApiError" new ApiError(200, 'OK', {}).status; // $ExpectType number new ApiError(200, 'OK', {}).statusText; // $ExpectType string new ApiError(200, 'OK', {}).response; // $ExpectType {} new ApiError(); // $ExpectError interface Response { data: number; } new ApiError<Response>(200, 'OK', { data: 0 }); // $ExpectType ApiError<Response> new ApiError<Response>(200, 'OK', { data: 0 }).name; // $ExpectType "ApiError" new ApiError<Response>(200, 'OK', { data: 0 }).status; // $ExpectType number new ApiError<Response>(200, 'OK', { data: 0 }).statusText; // $ExpectType string new ApiError<Response>(200, 'OK', { data: 0 }).response; // $ExpectType Response new ApiError<Response>(200, 'OK', {}); // $ExpectError } { // getJSON getJSON(new Response()); // $ExpectType Promise<any> getJSON(); // $ExpectError getJSON(0); // $ExpectError getJSON(new Response()).then((value: any) => value); // $ExpectType Promise<any> } { // createMiddleware createMiddleware(); // $ExpectType Middleware<{}, any, Dispatch<AnyAction>> createMiddleware({}); // $ExpectType Middleware<{}, any, Dispatch<AnyAction>> createMiddleware({ fetch }); // $ExpectType Middleware<{}, any, Dispatch<AnyAction>> createMiddleware({ ok: res => res.ok }); // $ExpectType Middleware<{}, any, Dispatch<AnyAction>> createMiddleware({ fetch, ok: res => res.ok }); // $ExpectType Middleware<{}, any, Dispatch<AnyAction>> } { // apiMiddleware // $ExpectType (next: Dispatch<AnyAction>) => (action: any) => any apiMiddleware({ getState: () => undefined, dispatch: (action: any) => action }); apiMiddleware(); // $ExpectError } { interface State { path: string; headers: HeadersInit; options: RequestInit; bailout: boolean; body: null; } class StateDrivenRSAACall implements RSAACall<State> { endpoint(state: State) { return state.path; } headers(state: State) { return state.headers; } options(state: State) { return state.options; } body(state: State) { return state.body; } bailout(state: State) { return state.bailout; } method: 'GET'; types: ['REQ_TYPE', 'SUCCESS_TYPE', 'FAILURE_TYPE']; } class PromiseStateDrivenRSAACall implements RSAACall<State> { endpoint(state: State) { return Promise.resolve(state.path); } headers(state: State) { return Promise.resolve(state.headers); } options(state: State) { return Promise.resolve(state.options); } body(state: State) { return Promise.resolve(state.body); } bailout(state: State) { return Promise.resolve(state.bailout); } method: 'GET'; types: ['REQ_TYPE', 'SUCCESS_TYPE', 'FAILURE_TYPE']; } class NonStateDrivenRSAACall implements RSAACall<State> { endpoint: '/test/endpoint'; method: 'GET'; headers: { 'Content-Type': 'application/json' }; options: { redirect: 'follow' }; bailout: true; types: ['REQ_TYPE', 'SUCCESS_TYPE', 'FAILURE_TYPE']; } } { const store: Store = createStore(() => undefined); const action: RSAAAction<any, string, number> = { [RSAA]: { endpoint: '/test/endpoint', method: 'GET', types: ['REQ_TYPE', 'SUCCESS_TYPE', 'FAILURE_TYPE'], }, }; store.dispatch(action); store.dispatch(action).then((action: RSAAResultAction<string, number>) => Promise.resolve()); store.dispatch(action).then(() => Promise.resolve()); store .dispatch(action) .then(action => (action.error ? Promise.reject() : Promise.resolve(action.payload))) .then((payload: string) => payload); store .dispatch(action) .then(action => (action.error ? Promise.reject() : Promise.resolve(action.meta))) .then((payload: number) => Promise.resolve()); store .dispatch(action) .then(action => (action.error ? Promise.reject() : Promise.resolve(action.payload))) .then((payload: number) => Promise.resolve()); // $ExpectError store.dispatch(action).then((action: string) => Promise.resolve()); // $ExpectError } { const requestDescriptor0: RSAARequestTypeDescriptor<number, number, number> = { type: '', payload: 0, meta: 0, }; const requestDescriptor1: RSAARequestTypeDescriptor<number, number, number> = { type: Symbol(), payload: (action: RSAAAction, state: number) => state, meta: (action: RSAAAction, state: number) => state, }; const requestDescriptor2: RSAARequestTypeDescriptor<number, number, number> = { type: 0, // $ExpectError payload: '', // $ExpectError meta: (action: RSAAAction, state: number) => '', // $ExpectError }; const requestDescriptor3: RSAARequestTypeDescriptor<number, number, number> = { type: Symbol(), payload: (action: RSAAAction, state: number) => Promise.resolve(state), meta: (action: RSAAAction, state: number) => Promise.resolve(state), }; const successDescriptor0: RSAASuccessTypeDescriptor<number, number, number> = { type: '', payload: 0, meta: 0, }; const successDescriptor1: RSAASuccessTypeDescriptor<number, number, number> = { type: Symbol(), payload: (action: RSAAAction, state: number, res: Response) => state, meta: (action: RSAAAction, state: number, res: Response) => state, }; const successDescriptor2: RSAASuccessTypeDescriptor<number, number, number> = { type: 0, // $ExpectError payload: '', // $ExpectError meta: (action: RSAAAction, state: number) => '', // $ExpectError }; const successDescriptor3: RSAASuccessTypeDescriptor<number, number, number> = { type: Symbol(), payload: (action: RSAAAction, state: number, res: Response) => Promise.resolve(state), meta: (action: RSAAAction, state: number, res: Response) => Promise.resolve(state), }; const failureDescriptor0: RSAAFailureTypeDescriptor<number, number, number> = { type: '', payload: 0, meta: 0, }; const failureDescriptor1: RSAAFailureTypeDescriptor<number, number, number> = { type: Symbol(), payload: (action: RSAAAction, state: number, res: Response) => state, meta: (action: RSAAAction, state: number, res: Response) => state, }; const failureDescriptor2: RSAAFailureTypeDescriptor<number, number, number> = { type: 0, // $ExpectError payload: '', // $ExpectError meta: (action: RSAAAction, state: number) => '', // $ExpectError }; const failureDescriptor3: RSAAFailureTypeDescriptor<number, number, number> = { type: Symbol(), payload: (action: RSAAAction, state: number, res: Response) => Promise.resolve(state), meta: (action: RSAAAction, state: number, res: Response) => Promise.resolve(state), }; } { const requestActionSimple: RSAARequestAction = { type: '', }; const requestActionWithPayload: RSAARequestAction<number> = { type: '', payload: 1, }; const requestActionWithIncorrectPayload: RSAARequestAction<number> = { type: '', payload: '', // $ExpectError }; const requestActionWithMeta: RSAARequestAction<never, number> = { type: '', meta: 1, }; // $ExpectError const requestActionWithMissingPayload: RSAARequestAction<number> = { type: '', }; const requestActionWithExtraneousMeta: RSAARequestAction<number> = { type: '', payload: 1, meta: 1, // $ExpectError }; const requestActionWithError: RSAARequestAction<number> = { type: '', error: true, payload: new InvalidRSAA(['']), }; const resultActionSimple: RSAAResultAction = { type: '', }; const resultActionWithPayload: RSAAResultAction<number> = { type: '', payload: 1, }; const resultActionWithIncorrectPayload: RSAAResultAction<number> = { type: '', payload: '', // $ExpectError }; const resultActionWithMeta: RSAAResultAction<never, number> = { type: '', meta: 1, }; // $ExpectError const resultActionWithMissingPayload: RSAAResultAction<number> = { type: '', }; const resultActionWithExtraneousMeta: RSAAResultAction<number> = { type: '', payload: 1, meta: 1, // $ExpectError }; const resultActionWithApiError: RSAAResultAction<number> = { type: '', error: true, payload: new ApiError(500, '', 1), }; const resultActionWithInternalError: RSAAResultAction<number> = { type: '', error: true, payload: new InternalError(''), }; const resultActionWithRequestError: RSAAResultAction<number> = { type: '', error: true, payload: new RequestError(''), }; // $ExpectError const resultActionWithMissingErrorPayload: RSAAResultAction<number> = { type: '', error: true, }; } { createAction(); // $ExpectError createAction({}); // $ExpectError // $ExpectType RSAAAction<any, any, any> createAction<any, any, any>({ endpoint: '/test/endpoint', method: 'GET', types: ['REQ_TYPE', 'SUCCESS_TYPE', 'FAILURE_TYPE'], }); }
the_stack
import { COMMA, DOWN_ARROW, ENTER } from '@angular/cdk/keycodes'; import { DebugElement } from '@angular/core'; import { ComponentFixture, discardPeriodicTasks, fakeAsync, flush, TestBed, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { combineReducers, Store, StoreModule } from '@ngrx/store'; import { of, ReplaySubject, Subject } from 'rxjs'; import { createDummies, dispatchKeyboardEvent, expectDom, fastTestSetup, sample, typeInElement, } from '../../../../test/helpers'; import { MockDialog } from '../../../../test/mocks/browser'; import { Asset, AssetTypes } from '../../../core/asset'; import { NoteSnippetTypes } from '../../../core/note'; import { MenuEvent, MenuService, NativeDialog, NativeDialogConfig, nativeDialogFileFilters, NativeDialogOpenResult, NativeDialogProperties, SharedModule, } from '../../shared'; import { Stack, StackModule, StackViewer } from '../../stack'; import { StackDummy } from '../../stack/dummies'; import { ChipDirective } from '../../ui/chips'; import { Dialog } from '../../ui/dialog'; import { UiModule } from '../../ui/ui.module'; import { NoteCollectionService, NoteItem, SelectNoteAction } from '../note-collection'; import { NoteItemDummy } from '../note-collection/dummies'; import { NoteSharedModule } from '../note-shared'; import { noteReducerMap } from '../note.reducer'; import { NoteStateWithRoot } from '../note.state'; import { NoteContentDummy, NoteSnippetContentDummy } from './dummies'; import { NoteCodeSnippetActionDialogActionType, NoteCodeSnippetActionDialogData, } from './note-code-snippet-action-dialog/note-code-snippet-action-dialog-data'; import { NoteCodeSnippetActionDialogResult } from './note-code-snippet-action-dialog/note-code-snippet-action-dialog-result'; import { NoteCodeSnippetActionDialogComponent } from './note-code-snippet-action-dialog/note-code-snippet-action-dialog.component'; import { NoteContent, NoteSnippetContent } from './note-content.model'; import { BlurSnippetAction, FocusSnippetAction, LoadNoteContentCompleteAction } from './note-editor.actions'; import { NoteEditorComponent } from './note-editor.component'; import { NoteEditorModule } from './note-editor.module'; import { NoteEditorService } from './note-editor.service'; import { NoteSnippetEditorInsertImageEvent, NoteSnippetEditorNewSnippetEvent } from './note-snippet-editor'; import { NoteSnippetListManager } from './note-snippet-list-manager'; import Spy = jasmine.Spy; describe('browser.note.noteEditor.NoteEditorComponent', () => { let fixture: ComponentFixture<NoteEditorComponent>; let component: NoteEditorComponent; let store: Store<NoteStateWithRoot>; let listManager: NoteSnippetListManager; let menu: MenuService; let mockDialog: MockDialog; let nativeDialog: NativeDialog; let noteEditor: NoteEditorService; let collection: NoteCollectionService; let stackViewer: StackViewer; let menuMessages: Subject<MenuEvent>; let selectedNoteStream: ReplaySubject<NoteItem>; const noteDummy = new NoteItemDummy(); const contentDummy = new NoteContentDummy(); const stackDummy = new StackDummy(); const getTitleTextareaEl = (): HTMLTextAreaElement => fixture.debugElement.query( By.css('.NoteEditor__titleTextarea > textarea'), ).nativeElement as HTMLTextAreaElement; const getStackChipDeList = (): DebugElement[] => fixture.debugElement.queryAll(By.css('.NoteEditor__stackChip')); const getNoteStacksInputEl = (): HTMLInputElement => fixture.debugElement.query(By.css('#note-stacks-input')).nativeElement as HTMLInputElement; function ensureSelectNoteAndLoadNoteContent( note: NoteItem = noteDummy.create(), content: NoteContent = contentDummy.create(), ): [NoteItem, NoteContent] { store.dispatch(new SelectNoteAction({ note })); store.dispatch(new LoadNoteContentCompleteAction({ note, content })); fixture.detectChanges(); listManager.addAllSnippetsFromContent(content); selectedNoteStream.next(note); fixture.detectChanges(); return [note, content]; } function provideStackDummies( stacks: Stack[] = createDummies(stackDummy, 5), ): Stack[] { // Remove all stacks. while (stackViewer.stacks.length > 0) { stackViewer.stacks.pop(); } stackViewer.stacks.push(...stacks); return stacks; } function activateSnippetAtIndex(index: number): void { store.dispatch(new FocusSnippetAction({ index })); } function deactivateSnippet(): void { store.dispatch(new BlurSnippetAction()); } function ignoreStackSearchAutocomplete(): void { component['subscribeStackAutocompleteSearch'] = jasmine.createSpy('subscribeStackAutocompleteSearch spy'); } fastTestSetup(); beforeAll(async () => { menu = jasmine.createSpyObj('menu', [ 'onMessage', ]); collection = jasmine.createSpyObj('collection', [ 'changeNoteTitle', 'getSelectedNote', 'changeNoteStacks', ]); await TestBed .configureTestingModule({ imports: [ NoopAnimationsModule, UiModule, SharedModule, StoreModule.forRoot({ note: combineReducers(noteReducerMap), }), StackModule, NoteSharedModule, NoteEditorModule, ...MockDialog.imports(), ], providers: [ { provide: MenuService, useValue: menu }, { provide: NoteCollectionService, useValue: collection }, ...MockDialog.providers(), ], }) .compileComponents(); }); beforeEach(() => { store = TestBed.get(Store); listManager = TestBed.get(NoteSnippetListManager); mockDialog = TestBed.get(Dialog); nativeDialog = TestBed.get(NativeDialog); noteEditor = TestBed.get(NoteEditorService); stackViewer = TestBed.get(StackViewer); menuMessages = new Subject<MenuEvent>(); selectedNoteStream = new ReplaySubject<NoteItem>(1); (menu.onMessage as Spy).and.returnValue(menuMessages.asObservable()); spyOn(listManager, 'handleSnippetRefEvent').and.callThrough(); (collection.getSelectedNote as Spy).and.callFake(() => selectedNoteStream.asObservable()); fixture = TestBed.createComponent(NoteEditorComponent); component = fixture.componentInstance; }); afterEach(() => { menuMessages.complete(); mockDialog.closeAll(); }); describe('stack input', () => { beforeEach(() => { ignoreStackSearchAutocomplete(); }); it('should show chips which from note stacks when ngOnInit.', () => { const selectedNote = noteDummy.create(); const stacks = provideStackDummies(); const noteStack = sample(stacks); selectedNote.stackIds.push(noteStack.name); ensureSelectNoteAndLoadNoteContent(selectedNote); const chipDeList = getStackChipDeList(); expect(chipDeList.length).toEqual(1); // Chip value must be stack name. const chipInstance = chipDeList[0].injector.get<ChipDirective>(ChipDirective); expect(chipInstance.value).toEqual(noteStack.name); // Chip name must be shown. expectDom(chipDeList[0].nativeElement as HTMLElement).toContainText(noteStack.name); }); it('should call \'changeNoteStacks\' from collection service when stack has been ' + 'added with ENTER keydown. (debounceTime=250ms)', fakeAsync(() => { const stacks = provideStackDummies(); const [selectedNote] = ensureSelectNoteAndLoadNoteContent(); const stack = sample(stacks); const stacksInputEl = getNoteStacksInputEl(); typeInElement(stack.name, getNoteStacksInputEl()); dispatchKeyboardEvent(stacksInputEl, 'keydown', ENTER); fixture.detectChanges(); tick(250); expect(collection.changeNoteStacks).toHaveBeenCalledWith(selectedNote, [stack.name]); })); it('should call \'changeNoteStacks\' from collection service when stack has been ' + 'added with COMMA keydown. (debounceTime=250ms)', fakeAsync(() => { ignoreStackSearchAutocomplete(); const stacks = provideStackDummies(); const [selectedNote] = ensureSelectNoteAndLoadNoteContent(); const stack = sample(stacks); const stacksInputEl = getNoteStacksInputEl(); typeInElement(stack.name, getNoteStacksInputEl()); dispatchKeyboardEvent(stacksInputEl, 'keydown', COMMA); fixture.detectChanges(); tick(250); expect(collection.changeNoteStacks).toHaveBeenCalledWith(selectedNote, [stack.name]); })); it('should call \'changeNoteStacks\' from collection service when stack has been ' + 'removed. (debounceTime=250ms)', fakeAsync(() => { ignoreStackSearchAutocomplete(); const stacks = provideStackDummies(); const [selectedNote] = ensureSelectNoteAndLoadNoteContent(); const prevStack = sample(stacks); const stacksInputEl = getNoteStacksInputEl(); // Add stack typeInElement(prevStack.name, getNoteStacksInputEl()); dispatchKeyboardEvent(stacksInputEl, 'keydown', COMMA); fixture.detectChanges(); tick(250); expect(collection.changeNoteStacks).toHaveBeenCalledWith(selectedNote, [prevStack.name]); // Remove stack getStackChipDeList()[0].injector .get<ChipDirective>(ChipDirective) .remove(); fixture.detectChanges(); tick(250); expect(collection.changeNoteStacks).toHaveBeenCalledWith(selectedNote, []); })); }); describe('title textarea', () => { it('should move focus first index of snippet when pressed enter in title textarea.', () => { fixture.detectChanges(); spyOn(listManager, 'focusTo'); dispatchKeyboardEvent(getTitleTextareaEl(), 'keydown', ENTER); expect(listManager.focusTo).toHaveBeenCalledWith(0); }); it('should move focus first index of snippet when pressed arrow down in ' + 'title textarea.', () => { fixture.detectChanges(); spyOn(listManager, 'focusTo'); dispatchKeyboardEvent(getTitleTextareaEl(), 'keydown', DOWN_ARROW); expect(listManager.focusTo).toHaveBeenCalledWith(0); }); }); describe('snippet list manager', () => { it('should set container element and view container ref on ngOnInit.', () => { spyOn(listManager, 'setContainerElement').and.callThrough(); spyOn(listManager, 'setViewContainerRef').and.callThrough(); fixture.detectChanges(); expect(listManager.setContainerElement).toHaveBeenCalledWith(component.snippetsList.nativeElement); expect(listManager.setViewContainerRef).toHaveBeenCalledWith(component._viewContainerRef); }); it('should focus title textarea when top focused out.', () => { fixture.detectChanges(); listManager['_topFocusOut'].next(); fixture.detectChanges(); expect(document.activeElement).toEqual(component.titleTextarea.nativeElement); }); }); describe('MenuEvent.NEW_TEXT_SNIPPET', () => { it('should not handle create new snippet event if active snippet index is \'null\'.', () => { fixture.detectChanges(); ensureSelectNoteAndLoadNoteContent(); deactivateSnippet(); fixture.detectChanges(); menuMessages.next(MenuEvent.NEW_TEXT_SNIPPET); expect(listManager.handleSnippetRefEvent).not.toHaveBeenCalled(); }); it('should handle create new snippet event when active snippet index is exists.', () => { fixture.detectChanges(); ensureSelectNoteAndLoadNoteContent(); activateSnippetAtIndex(2); fixture.detectChanges(); menuMessages.next(MenuEvent.NEW_TEXT_SNIPPET); expect(listManager.handleSnippetRefEvent).toHaveBeenCalled(); const event = (listManager.handleSnippetRefEvent as Spy) .calls.mostRecent().args[0] as NoteSnippetEditorNewSnippetEvent; // noinspection SuspiciousInstanceOfGuard expect(event instanceof NoteSnippetEditorNewSnippetEvent).toBe(true); expect(event.payload.snippet).toEqual({ type: NoteSnippetTypes.TEXT, value: '', } as NoteSnippetContent); }); }); describe('MenuEvent.NEW_CODE_SNIPPET', () => { it('should open NoteCodeSnippetActionDialog when active snippet index is exists. ' + 'And handle create new snippet when user close dialog with result.', () => { fixture.detectChanges(); ensureSelectNoteAndLoadNoteContent(); activateSnippetAtIndex(0); fixture.detectChanges(); menuMessages.next(MenuEvent.NEW_CODE_SNIPPET); // Expect dialog. const actionDialog = mockDialog.getByComponent<NoteCodeSnippetActionDialogComponent, NoteCodeSnippetActionDialogData, NoteCodeSnippetActionDialogResult>( NoteCodeSnippetActionDialogComponent, ); expect(actionDialog).toBeDefined(); expect(actionDialog.config.data.actionType).toEqual('create' as NoteCodeSnippetActionDialogActionType); actionDialog.close({ codeLanguageId: 'typescript', codeFileName: 'i-love-ts.ts', }); const event = ( listManager.handleSnippetRefEvent as Spy ).calls.mostRecent().args[0] as NoteSnippetEditorNewSnippetEvent; expect(listManager.handleSnippetRefEvent).toHaveBeenCalled(); // noinspection SuspiciousInstanceOfGuard expect(event instanceof NoteSnippetEditorNewSnippetEvent).toBe(true); expect(event.payload.snippet).toEqual({ type: NoteSnippetTypes.CODE, value: '', codeLanguageId: 'typescript', codeFileName: 'i-love-ts.ts', } as NoteSnippetContent); }); }); describe('MenuEvent.INSERT_IMAGE', () => { let snippets: NoteSnippetContent[]; beforeEach(() => { fixture.detectChanges(); const snippetDummy = new NoteSnippetContentDummy(); snippets = [ snippetDummy.create(NoteSnippetTypes.TEXT), snippetDummy.create(NoteSnippetTypes.CODE), ]; const content = { snippets } as NoteContent; store.dispatch(new LoadNoteContentCompleteAction({ note: new NoteItemDummy().create(), content, })); listManager.addAllSnippetsFromContent(content); fixture.detectChanges(); }); it('should show file open dialog when insert image event received while type of active snippet is ' + '\'TEXT\'. And dispatch NoteSnippetEditorInsertImageEvent when user select file.', fakeAsync(() => { const selectedNote = noteDummy.create(); const content = contentDummy.create(); content.snippets[0] = new NoteSnippetContentDummy().create(NoteSnippetTypes.TEXT); ensureSelectNoteAndLoadNoteContent(selectedNote, content); activateSnippetAtIndex(0); fixture.detectChanges(); spyOn(nativeDialog, 'showOpenDialog').and.returnValue(of({ isSelected: true, filePaths: ['/foo/bar/assets/some-image.png'], } as NativeDialogOpenResult)); spyOn(noteEditor, 'copyAssetFile').and.returnValue(of({ fileNameWithoutExtension: 'some-image', relativePathToWorkspaceDir: './some-image.png', } as Asset)); menuMessages.next(MenuEvent.INSERT_IMAGE); flush(); flush(); flush(); expect(nativeDialog.showOpenDialog).toHaveBeenCalledWith({ message: 'Choose an image:', properties: NativeDialogProperties.OPEN_FILE, fileFilters: [nativeDialogFileFilters.IMAGES], } as NativeDialogConfig); expect(noteEditor.copyAssetFile).toHaveBeenCalledWith( AssetTypes.IMAGE, selectedNote.contentFilePath, '/foo/bar/assets/some-image.png', ); expect(listManager.handleSnippetRefEvent).toHaveBeenCalled(); const event = ( listManager.handleSnippetRefEvent as Spy ).calls.first().args[0] as NoteSnippetEditorInsertImageEvent; // noinspection SuspiciousInstanceOfGuard expect(event instanceof NoteSnippetEditorInsertImageEvent).toBe(true); expect(event.payload.fileName).toEqual('some-image'); expect(event.payload.filePath).toEqual('./some-image.png'); discardPeriodicTasks(); })); }); describe('Note title', () => { it('should update note title when selected note changes.', () => { const prevSelectedNote = noteDummy.create(); ensureSelectNoteAndLoadNoteContent(prevSelectedNote); fixture.detectChanges(); expect(getTitleTextareaEl().value).toContain(prevSelectedNote.title); const nextSelectedNote = noteDummy.create(); selectedNoteStream.next(nextSelectedNote); fixture.detectChanges(); expect(getTitleTextareaEl().value).toContain(nextSelectedNote.title); }); it('should change note title with collection service when title value changes ' + 'after 250ms.', fakeAsync(() => { (collection.changeNoteTitle as Spy).and.callFake(() => Promise.resolve(null)); const [selectedNote] = ensureSelectNoteAndLoadNoteContent(); fixture.detectChanges(); typeInElement('New Title', getTitleTextareaEl()); fixture.detectChanges(); tick(250); flush(); expect(collection.changeNoteTitle).toHaveBeenCalledWith(selectedNote, 'New Title'); })); }); });
the_stack
import * as ts from 'typescript' import { FunctionType, SyntaxType } from '@creditkarma/thrift-parser' import { DefinitionType, IRenderState } from '../../types' import { APPLICATION_EXCEPTION, COMMON_IDENTIFIERS, PROTOCOL_EXCEPTION, THRIFT_TYPES, } from './identifiers' import { createArrayType, createBooleanType, createBufferType, createNumberType, createStringType, createVoidType, } from '../shared/types' import { Resolver } from '../../resolver' import { looseName, strictName } from './struct/utils' export * from '../shared/types' export type TProtocolException = | 'UNKNOWN' | 'INVALID_DATA' | 'NEGATIVE_SIZE' | 'SIZE_LIMIT' | 'BAD_VERSION' | 'NOT_IMPLEMENTED' | 'DEPTH_LIMIT' export type TApplicationException = | 'UNKNOWN' | 'UNKNOWN_METHOD' | 'INVALID_MESSAGE_TYPE' | 'WRONG_METHOD_NAME' | 'BAD_SEQUENCE_ID' | 'MISSING_RESULT' | 'INTERNAL_ERROR' | 'PROTOCOL_ERROR' | 'INVALID_TRANSFORM' | 'INVALID_PROTOCOL' | 'UNSUPPORTED_CLIENT_TYPE' export function protocolException( exceptionType: TProtocolException, ): ts.Identifier { switch (exceptionType) { case 'UNKNOWN': return PROTOCOL_EXCEPTION.UNKNOWN case 'INVALID_DATA': return PROTOCOL_EXCEPTION.INVALID_DATA case 'NEGATIVE_SIZE': return PROTOCOL_EXCEPTION.NEGATIVE_SIZE case 'SIZE_LIMIT': return PROTOCOL_EXCEPTION.SIZE_LIMIT case 'BAD_VERSION': return PROTOCOL_EXCEPTION.BAD_VERSION case 'NOT_IMPLEMENTED': return PROTOCOL_EXCEPTION.NOT_IMPLEMENTED case 'DEPTH_LIMIT': return PROTOCOL_EXCEPTION.DEPTH_LIMIT default: const msg: never = exceptionType throw new Error(`Non-exhaustive match for: ${msg}`) } } export function applicationException( exceptionType: TApplicationException, ): ts.Identifier { switch (exceptionType) { case 'UNKNOWN': return APPLICATION_EXCEPTION.UNKNOWN case 'UNKNOWN_METHOD': return APPLICATION_EXCEPTION.UNKNOWN_METHOD case 'INVALID_MESSAGE_TYPE': return APPLICATION_EXCEPTION.INVALID_MESSAGE_TYPE case 'WRONG_METHOD_NAME': return APPLICATION_EXCEPTION.WRONG_METHOD_NAME case 'BAD_SEQUENCE_ID': return APPLICATION_EXCEPTION.BAD_SEQUENCE_ID case 'MISSING_RESULT': return APPLICATION_EXCEPTION.MISSING_RESULT case 'INTERNAL_ERROR': return APPLICATION_EXCEPTION.INTERNAL_ERROR case 'PROTOCOL_ERROR': return APPLICATION_EXCEPTION.PROTOCOL_ERROR case 'INVALID_TRANSFORM': return APPLICATION_EXCEPTION.INVALID_TRANSFORM case 'INVALID_PROTOCOL': return APPLICATION_EXCEPTION.INVALID_PROTOCOL case 'UNSUPPORTED_CLIENT_TYPE': return APPLICATION_EXCEPTION.UNSUPPORTED_CLIENT_TYPE default: const msg: never = exceptionType throw new Error(`Non-exhaustive match for: ${msg}`) } } function thriftTypeForIdentifier( definition: DefinitionType, state: IRenderState, ): ts.Identifier { switch (definition.type) { case SyntaxType.ConstDefinition: throw new TypeError( `Identifier ${definition.name.value} is a value being used as a type`, ) case SyntaxType.ServiceDefinition: throw new TypeError( `Service ${definition.name.value} is being used as a type`, ) case SyntaxType.StructDefinition: case SyntaxType.UnionDefinition: case SyntaxType.ExceptionDefinition: return THRIFT_TYPES.STRUCT case SyntaxType.EnumDefinition: return THRIFT_TYPES.I32 case SyntaxType.TypedefDefinition: return thriftTypeForFieldType(definition.definitionType, state) default: const msg: never = definition throw new Error(`Non-exhaustive match for: ${msg}`) } } /** * Gets the type access for the 'Thrift' object for a given FieldType. */ export function thriftTypeForFieldType( fieldType: FunctionType, state: IRenderState, ): ts.Identifier { switch (fieldType.type) { case SyntaxType.Identifier: const result = Resolver.resolveIdentifierDefinition(fieldType, { currentNamespace: state.currentNamespace, namespaceMap: state.project.namespaces, }) return thriftTypeForIdentifier(result.definition, state) case SyntaxType.SetType: return THRIFT_TYPES.SET case SyntaxType.MapType: return THRIFT_TYPES.MAP case SyntaxType.ListType: return THRIFT_TYPES.LIST case SyntaxType.BinaryKeyword: case SyntaxType.StringKeyword: return THRIFT_TYPES.STRING case SyntaxType.BoolKeyword: return THRIFT_TYPES.BOOL case SyntaxType.DoubleKeyword: return THRIFT_TYPES.DOUBLE case SyntaxType.I8Keyword: case SyntaxType.ByteKeyword: return THRIFT_TYPES.BYTE case SyntaxType.I16Keyword: return THRIFT_TYPES.I16 case SyntaxType.I32Keyword: return THRIFT_TYPES.I32 case SyntaxType.I64Keyword: return THRIFT_TYPES.I64 case SyntaxType.VoidKeyword: return THRIFT_TYPES.VOID default: const msg: never = fieldType throw new Error(`Non-exhaustive match for: ${msg}`) } } /** * Creates type annotations for Thrift types * * EXAMPLE * * // thrift * const bool FALSE_CONST = false * * // typescript * const FALSE_CONST: boolean = false * * This function provides the ': boolean' bit. * * Container types: * * SetType | MapType | ListType * * Base types: * * SyntaxType.StringKeyword | SyntaxType.DoubleKeyword | SyntaxType.BoolKeyword | * SyntaxType.I8Keyword | SyntaxType.I16Keyword | SyntaxType.I32Keyword | * SyntaxType.I64Keyword | SyntaxType.BinaryKeyword | SyntaxType.ByteKeyword; * * Function types: * * SyntaxType.VoidKeyword */ function typeNodeForIdentifier( definition: DefinitionType, name: string, state: IRenderState, loose: boolean = false, ): ts.TypeNode { switch (definition.type) { case SyntaxType.StructDefinition: case SyntaxType.ExceptionDefinition: case SyntaxType.UnionDefinition: if (loose) { return ts.createTypeReferenceNode( ts.createIdentifier( looseName(name, definition.type, state), ), undefined, ) } else { return ts.createTypeReferenceNode( ts.createIdentifier( strictName(name, definition.type, state), ), undefined, ) } default: return ts.createTypeReferenceNode( ts.createIdentifier( Resolver.resolveIdentifierName(name, { currentNamespace: state.currentNamespace, currentDefinitions: state.currentDefinitions, namespaceMap: state.project.namespaces, }).fullName, ), undefined, ) } } export function typeNodeForFieldType( fieldType: FunctionType, state: IRenderState, loose: boolean = false, ): ts.TypeNode { switch (fieldType.type) { case SyntaxType.Identifier: const result = Resolver.resolveIdentifierDefinition(fieldType, { currentNamespace: state.currentNamespace, namespaceMap: state.project.namespaces, }) return typeNodeForIdentifier( result.definition, fieldType.value, state, loose, ) case SyntaxType.SetType: return ts.createTypeReferenceNode(COMMON_IDENTIFIERS.Set, [ typeNodeForFieldType(fieldType.valueType, state, loose), ]) case SyntaxType.MapType: return ts.createTypeReferenceNode(COMMON_IDENTIFIERS.Map, [ typeNodeForFieldType(fieldType.keyType, state, loose), typeNodeForFieldType(fieldType.valueType, state, loose), ]) case SyntaxType.ListType: return createArrayType( typeNodeForFieldType(fieldType.valueType, state, loose), ) case SyntaxType.StringKeyword: return createStringType() case SyntaxType.BoolKeyword: return createBooleanType() case SyntaxType.I64Keyword: if (loose === true) { return ts.createUnionTypeNode([ createNumberType(), createStringType(), ts.createTypeReferenceNode( COMMON_IDENTIFIERS.Int64, undefined, ), ]) } else { return ts.createTypeReferenceNode( COMMON_IDENTIFIERS.Int64, undefined, ) } case SyntaxType.BinaryKeyword: if (loose === true) { return ts.createUnionTypeNode([ createStringType(), createBufferType(), ]) } else { return createBufferType() } case SyntaxType.DoubleKeyword: case SyntaxType.I8Keyword: case SyntaxType.I16Keyword: case SyntaxType.I32Keyword: case SyntaxType.ByteKeyword: return createNumberType() case SyntaxType.VoidKeyword: return createVoidType() default: const msg: never = fieldType throw new Error(`Non-exhaustive match for: ${msg}`) } }
the_stack
import ts from 'typescript'; import * as guards from './guards'; import * as symbol_ from './symbol'; import * as utils from './utils'; type TypedNode = ts.Node & { readonly type?: ts.TypeNode }; type MaybeTypedNode = ts.Node & { readonly type?: ts.TypeNode }; function getIntrinsicName(type: ts.Type): string | undefined { // tslint:disable-next-line no-any return (type as any).intrinsicName; } export function getTypeNode(node: TypedNode): ts.TypeNode; export function getTypeNode(node: MaybeTypedNode): ts.TypeNode | undefined; export function getTypeNode(node: TypedNode | MaybeTypedNode): ts.TypeNode | undefined { return utils.getValueOrUndefined(node.type); } export function getTypeNodeOrThrow(node: MaybeTypedNode): ts.TypeNode { return utils.throwIfNullOrUndefined(getTypeNode(node), 'type node'); } export function getContextualType(typeChecker: ts.TypeChecker, node: ts.Expression): ts.Type | undefined { return utils.getValueOrUndefined(typeChecker.getContextualType(node)); } export function getTypeFromTypeNode(typeChecker: ts.TypeChecker, typeNode: ts.TypeNode): ts.Type { return typeChecker.getTypeFromTypeNode(typeNode); } export function getType(typeChecker: ts.TypeChecker, node: ts.Node): ts.Type { // tslint:disable-next-line no-any const typeNode = ts.isFunctionLike(node) ? undefined : (getTypeNode(node as any) as ts.TypeNode | undefined); if (typeNode !== undefined) { return typeChecker.getTypeFromTypeNode(typeNode); } const type = typeChecker.getTypeAtLocation(node); if (isAny(type) && guards.isExpression(node)) { const contextualType = getContextualType(typeChecker, node); if (contextualType !== undefined && !isAny(contextualType)) { return contextualType; } } return type; } export function getConstraint(type: ts.Type): ts.Type | undefined { return utils.getValueOrUndefined(type.getConstraint()); } export function getTypeAtLocation(typeChecker: ts.TypeChecker, symbol: ts.Symbol, node: ts.Node): ts.Type { return typeChecker.getTypeOfSymbolAtLocation(symbol, node); } export function typeToTypeNode( typeChecker: ts.TypeChecker, type: ts.Type, node?: ts.Declaration, ): ts.TypeNode | undefined { return typeChecker.typeToTypeNode(type, node); } export function typeToTypeNodeOrThrow(typeChecker: ts.TypeChecker, type: ts.Type, node?: ts.Declaration): ts.TypeNode { return utils.throwIfNullOrUndefined(typeToTypeNode(typeChecker, type, node), 'type node'); } export function getSymbol(type: ts.Type): ts.Symbol | undefined { return utils.getValueOrUndefined(type.getSymbol()); } export function getAliasSymbol(type: ts.Type): ts.Symbol | undefined { return utils.getValueOrUndefined(type.aliasSymbol); } export function getAliasTypeArguments(type: ts.Type): readonly ts.Type[] | undefined { return utils.getValueOrUndefined(type.aliasTypeArguments); } export function getAliasTypeArgumentsArray(type: ts.Type): readonly ts.Type[] { return utils.getArray(getAliasTypeArguments(type)); } export function getSymbolOrThrow(type: ts.Type): ts.Symbol { return utils.throwIfNullOrUndefined(getSymbol(type), 'symbol'); } function getDefaultTypeFormatFlags(node?: ts.Node): ts.TypeFormatFlags { let formatFlags = ts.TypeFormatFlags.UseTypeOfFunction | ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseFullyQualifiedType | ts.TypeFormatFlags.WriteTypeArgumentsOfSignature; if (node !== undefined && node.kind === ts.SyntaxKind.TypeAliasDeclaration) { formatFlags |= ts.TypeFormatFlags.InTypeAlias; } return formatFlags; } export function getProperties(type: ts.Type): readonly ts.Symbol[] { return type.getProperties(); } export function getConstructSignatures(type: ts.Type): readonly ts.Signature[] { return type.getConstructSignatures(); } export function getProperty(type: ts.Type, name: string): ts.Symbol | undefined { return utils.getValueOrUndefined(type.getProperty(name)); } export function getText( typeChecker: ts.TypeChecker, type: ts.Type, node?: ts.Node, flags: ts.TypeFormatFlags = getDefaultTypeFormatFlags(node), ): string { return typeChecker.typeToString(type, node, flags); } export function getBaseTypes(type: ts.Type): readonly ts.Type[] | undefined { return utils.getValueOrUndefined(type.getBaseTypes()); } export function getBaseTypesArray(type: ts.Type): readonly ts.Type[] { return utils.getArray(getBaseTypes(type)); } function isTypeFlag(type: ts.Type, flag: ts.TypeFlags): boolean { return (type.flags & flag) === flag; } function isObjectFlag(type: ts.Type, flag: ts.ObjectFlags): boolean { return isObjectType(type) && (type.objectFlags & flag) === flag; } function hasTypeFlag(type: ts.Type, flag: ts.TypeFlags): boolean { return (type.flags & flag) !== 0; } export function getAllTypes(type: ts.Type): readonly ts.Type[] { const unionTypes = getUnionTypes(type); if (unionTypes !== undefined) { return unionTypes.reduce<readonly ts.Type[]>((acc, unionType) => acc.concat(getAllTypes(unionType)), []); } const intersectionTypes = getIntersectionTypes(type); if (intersectionTypes !== undefined) { return intersectionTypes.reduce<readonly ts.Type[]>((acc, unionType) => acc.concat(getAllTypes(unionType)), []); } return [type]; } export function getTypes(type: ts.Type, isType: (type: ts.Type) => boolean): readonly ts.Type[] { if (isType(type)) { return [type]; } const unionTypes = getUnionTypes(type); if (unionTypes !== undefined) { return unionTypes.reduce<readonly ts.Type[]>((acc, unionType) => acc.concat(getTypes(unionType, isType)), []); } const intersectionTypes = getIntersectionTypes(type); if (intersectionTypes !== undefined) { return intersectionTypes.reduce<readonly ts.Type[]>( (acc, unionType) => acc.concat(getTypes(unionType, isType)), [], ); } return []; } export function isSymbolic(type: ts.Type): boolean { return !(isPrimitiveish(type) || isIntersection(type) || isUnion(type) || isTuple(type)); } export function isObjectType(type: ts.Type): type is ts.ObjectType { return isTypeFlag(type, ts.TypeFlags.Object); } export function isTypeReference(type: ts.Type): type is ts.TypeReference { return isObjectFlag(type, ts.ObjectFlags.Reference); } export function isTupleType(type: ts.Type): type is ts.TupleType { return isObjectFlag(type, ts.ObjectFlags.Tuple); } export function isTuple(type: ts.Type): type is ts.TupleTypeReference { return isTypeReference(type) && isTupleType(type.target); } export function hasTuple(type: ts.Type): boolean { return hasType(type, isTuple); } export function getTupleTypes(type: ts.Type): readonly ts.Type[] { return getTypes(type, isTuple); } // If undefined => not a tuple type export function getTupleElements(type: ts.Type): readonly ts.Type[] | undefined { return isTuple(type) ? utils.getArray(type.typeArguments) : undefined; } export function getTypeArguments(type: ts.Type): readonly ts.Type[] | undefined { return isTypeReference(type) ? utils.getValueOrUndefined(type.typeArguments) : undefined; } export function getTypeArgumentsArray(type: ts.Type): readonly ts.Type[] { return utils.getArray(getTypeArguments(type)); } export function getTypeArgumentsOrThrow(type: ts.Type): readonly ts.Type[] { return utils.throwIfNullOrUndefined(getTypeArguments(type), 'type arguments'); } export function isAny(type: ts.Type): boolean { return hasTypeFlag(type, ts.TypeFlags.Any); } export function isErrorType(type: ts.Type): boolean { return isAny(type) && getIntrinsicName(type) === 'error'; } export function isUnion(type: ts.Type): type is ts.UnionType { // tslint:disable-next-line no-any return (type as any).isUnion === undefined ? false : type.isUnion(); } export function getUnionTypes(type: ts.Type): readonly ts.Type[] | undefined { return isUnion(type) ? utils.getArray(type.types) : undefined; } export function getUnionTypesArray(type: ts.Type): readonly ts.Type[] { return utils.getArray(getUnionTypes(type)); } export function isIntersection(type: ts.Type): type is ts.IntersectionType { // tslint:disable-next-line no-any return (type as any).isIntersection === undefined ? false : type.isIntersection(); } export function getIntersectionTypes(type: ts.Type): readonly ts.Type[] | undefined { return isIntersection(type) ? utils.getArray(type.types) : undefined; } export function getIntersectionTypesArray(type: ts.Type): readonly ts.Type[] { return utils.getArray(getIntersectionTypes(type)); } export function hasUnionType(type: ts.Type, isType: (type: ts.Type) => boolean): boolean { const unionTypes = getUnionTypes(type); return unionTypes !== undefined && unionTypes.some(isType); } export function hasIntersectionType(type: ts.Type, isType: (type: ts.Type) => boolean): boolean { const types = getIntersectionTypes(type); return types !== undefined && types.some(isType); } export function hasType(type: ts.Type, isType: (type: ts.Type) => boolean): boolean { return isType(type) || hasUnionType(type, isType) || hasIntersectionType(type, isType); } export function isOnlyType(type: ts.Type, isType: (type: ts.Type) => boolean): boolean { if (isType(type)) { return true; } const unionTypes = getUnionTypes(type); if (unionTypes !== undefined && unionTypes.every((tpe) => isOnlyType(tpe, isType))) { return true; } const intersectionTypes = getIntersectionTypes(type); if (intersectionTypes !== undefined && intersectionTypes.every((tpe) => isOnlyType(tpe, isType))) { return true; } return false; } export function isSame(a: ts.Type | undefined, b: ts.Type | undefined): boolean { return ( a !== undefined && b !== undefined && (a === b || (isOnlyBooleanish(a) && isOnlyBooleanish(b)) || (isOnlyStringish(a) && isOnlyStringish(b)) || (isOnlyNumberish(a) && isOnlyNumberish(b)) || (isOnlySymbolish(a) && isOnlySymbolish(b))) ); } export function isOnly(type: ts.Type): boolean { return [...new Set(getAllTypes(type))].length === 0; } export function isNull(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.Null); } export function isOnlyNull(type: ts.Type): boolean { return isOnlyType(type, isNull); } export function hasNull(type: ts.Type): boolean { return hasType(type, isNull); } export function isUndefined(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.Undefined); } export function isOnlyUndefined(type: ts.Type): boolean { return isOnlyType(type, isUndefined); } export function hasUndefined(type: ts.Type): boolean { return hasType(type, isUndefined); } export function isUndefinedish(type: ts.Type): boolean { return isUndefined(type) || isVoid(type); } export function isOnlyUndefinedish(type: ts.Type): boolean { return isOnlyType(type, isUndefinedish); } export function hasUndefinedish(type: ts.Type): boolean { return hasType(type, isUndefinedish); } export function isNullable(type: ts.Type): boolean { const types = getUnionTypes(type); return ( isNull(type) || isUndefined(type) || (types !== undefined && types.some((tpe) => isNull(tpe) || isUndefined(tpe))) ); } export function isNumber(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.Number); } export function isOnlyNumber(type: ts.Type): boolean { return isOnlyType(type, isNumber); } export function hasNumber(type: ts.Type): boolean { return hasType(type, isNumber); } export function isNumberLike(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.NumberLike); } export function isOnlyNumberLike(type: ts.Type): boolean { return isOnlyType(type, isNumberLike); } export function hasNumberLike(type: ts.Type): boolean { return hasType(type, isNumberLike); } export function isNumberLiteral(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.NumberLiteral); } export function isOnlyNumberLiteral(type: ts.Type): boolean { return isOnlyType(type, isNumberLiteral); } export function hasNumberLiteral(type: ts.Type): boolean { return hasType(type, isNumberLiteral); } export function isNumberish(type: ts.Type): boolean { return hasTypeFlag(type, ts.TypeFlags.NumberLike); } export function isOnlyNumberish(type: ts.Type): boolean { return isOnlyType(type, isNumberish); } export function hasNumberish(type: ts.Type): boolean { return hasType(type, isNumberish); } export function isString(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.String); } export function isOnlyString(type: ts.Type): boolean { return isOnlyType(type, isString); } export function hasString(type: ts.Type): boolean { return hasType(type, isString); } export function isStringLike(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.StringLike); } export function isOnlyStringLike(type: ts.Type): boolean { return isOnlyType(type, isStringLike); } export function hasStringLike(type: ts.Type): boolean { return hasType(type, isStringLike); } export function isStringLiteral(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.StringLiteral); } export function isOnlyStringLiteral(type: ts.Type): boolean { return isOnlyType(type, isStringLiteral); } export function hasStringLiteral(type: ts.Type): boolean { return hasType(type, isStringLiteral); } export function isStringish(type: ts.Type): boolean { return hasTypeFlag(type, ts.TypeFlags.StringLike); } export function isOnlyStringish(type: ts.Type): boolean { return isOnlyType(type, isStringish); } export function hasStringish(type: ts.Type): boolean { return hasType(type, isStringish); } export function isBoolean(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.Boolean); } export function isOnlyBoolean(type: ts.Type): boolean { return isOnlyType(type, isBoolean); } export function hasBoolean(type: ts.Type): boolean { return hasType(type, isBoolean); } export function isBooleanLike(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.BooleanLike); } export function isOnlyBooleanLike(type: ts.Type): boolean { return isOnlyType(type, isBooleanLike); } export function hasBooleanLike(type: ts.Type): boolean { return hasType(type, isBooleanLike); } export function isBooleanLiteral(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.BooleanLiteral); } export function isOnlyBooleanLiteral(type: ts.Type): boolean { return isOnlyType(type, isBooleanLiteral); } export function hasBooleanLiteral(type: ts.Type): boolean { return hasType(type, isBooleanLiteral); } export function isBooleanFalse(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.BooleanLiteral) && getIntrinsicName(type) === 'false'; } export function isOnlyBooleanFalse(type: ts.Type): boolean { return isOnlyType(type, isBooleanFalse); } export function hasBooleanFalse(type: ts.Type): boolean { return hasType(type, isBooleanFalse); } export function isBooleanish(type: ts.Type): boolean { return hasTypeFlag(type, ts.TypeFlags.BooleanLike); } export function isOnlyBooleanish(type: ts.Type): boolean { return isOnlyType(type, isBooleanish); } export function hasBooleanish(type: ts.Type): boolean { return hasType(type, isBooleanish); } export function isSymbol(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.ESSymbol); } export function isOnlySymbol(type: ts.Type): boolean { return isOnlyType(type, isSymbol); } export function hasSymbol(type: ts.Type): boolean { return hasType(type, isSymbol); } export function isSymbolLike(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.ESSymbolLike); } export function isOnlySymbolLike(type: ts.Type): boolean { return isOnlyType(type, isSymbolLike); } export function hasSymbolLike(type: ts.Type): boolean { return hasType(type, isSymbolLike); } export function isSymbolish(type: ts.Type): boolean { return hasTypeFlag(type, ts.TypeFlags.ESSymbolLike); } export function isOnlySymbolish(type: ts.Type): boolean { return isOnlyType(type, isSymbolish); } export function hasSymbolish(type: ts.Type): boolean { return hasType(type, isSymbolish); } export function isPrimitive(type: ts.Type): boolean { return isUndefined(type) || isNull(type) || isNumber(type) || isBoolean(type) || isString(type) || isSymbol(type); } export function isOnlyPrimitive(type: ts.Type): boolean { return isOnlyType(type, isPrimitive); } export function hasPrimitive(type: ts.Type): boolean { return hasType(type, isPrimitive); } export function isPrimitiveLike(type: ts.Type): boolean { return ( isUndefined(type) || isNull(type) || isNumberLike(type) || isBooleanLike(type) || isStringLike(type) || isSymbolLike(type) ); } export function isOnlyPrimitiveLike(type: ts.Type): boolean { return isOnlyType(type, isPrimitiveLike); } export function hasPrimitiveLike(type: ts.Type): boolean { return hasType(type, isPrimitiveLike); } export function isPrimitiveish(type: ts.Type): boolean { return ( isUndefined(type) || isNull(type) || isNumberish(type) || isBooleanish(type) || isStringish(type) || isSymbolish(type) || isVoidish(type) ); } export function isOnlyPrimitiveish(type: ts.Type): boolean { return isOnlyType(type, isPrimitiveish); } export function hasPrimitiveish(type: ts.Type): boolean { return hasType(type, isPrimitive); } export function isOnlyObject(type: ts.Type): boolean { return isOnlyType(type, (value) => !isPrimitiveish(value)); } export function isArray(type: ts.Type): boolean { const typeSymbol = getSymbol(type); const typeArguments = getTypeArguments(type); if (typeSymbol === undefined || typeArguments === undefined) { return false; } return ( (symbol_.getName(typeSymbol) === 'Array' || symbol_.getName(typeSymbol) === 'ReadonlyArray') && typeArguments.length === 1 ); } export function isOnlyArray(type: ts.Type): boolean { return isOnlyType(type, isArray); } export function hasArray(type: ts.Type): boolean { return hasType(type, isArray); } export function isArrayish(type: ts.Type): boolean { return isArray(type) || isTuple(type); } export function isOnlyArrayish(type: ts.Type): boolean { return isOnlyType(type, isArrayish); } export function hasArrayish(type: ts.Type): boolean { return hasType(type, isArrayish); } export function getArrayType(type: ts.Type): ts.Type | undefined { if (!isArray(type)) { return undefined; } const typeArguments = getTypeArgumentsOrThrow(type); return typeArguments[0]; } export function getArrayTypeOrThrow(type: ts.Type): ts.Type { return utils.throwIfNullOrUndefined(getArrayType(type), 'array type'); } export function getArrayTypes(type: ts.Type): readonly ts.Type[] { return getTypes(type, isArray); } export function isVoid(type: ts.Type): boolean { return isTypeFlag(type, ts.TypeFlags.Void); } export function isOnlyVoid(type: ts.Type): boolean { return isOnlyType(type, isVoid); } export function hasVoid(type: ts.Type): boolean { return hasType(type, isVoid); } export function isVoidish(type: ts.Type): boolean { return isVoid(type) || isUndefined(type); } export function isOnlyVoidish(type: ts.Type): boolean { return isOnlyType(type, isVoidish); } export function hasVoidish(type: ts.Type): boolean { return hasType(type, isVoidish); } export function getCallSignatures(type: ts.Type): readonly ts.Signature[] { return type.getCallSignatures(); } export function getNonNullableType(type: ts.Type): ts.Type { return type.getNonNullableType(); } export function filterUnion(checker: ts.TypeChecker, type: ts.Type, filter: (type: ts.Type) => boolean): ts.Type { const types = getUnionTypes(type); if (types === undefined) { return type; } // tslint:disable-next-line no-any return (checker as any).getUnionType(types.filter(filter)); }
the_stack
import { Component, ViewEncapsulation, Input, AfterViewInit, ViewChild, OnDestroy, EventEmitter, Output, ContentChildren, HostListener, AfterViewChecked, ElementRef, Renderer2 } from '@angular/core'; import type {QueryList} from '@angular/core'; import {CdkScrollable} from '@angular/cdk/scrolling'; import {Subject} from 'rxjs'; import {HcScrollNavComponent} from '../nav/scroll-nav.component'; import {takeUntil} from 'rxjs/operators'; import {differenceBy} from 'lodash'; import {ScrollNavTargetDirective} from './scroll-nav-target.directive'; /** Contains scrollable content that is navigable via `hc-scroll-nav` links. */ @Component({ selector: 'hc-scroll-nav-content', encapsulation: ViewEncapsulation.None, styleUrls: ['scroll-nav-content.component.scss'], templateUrl: 'scroll-nav-content.component.html' }) export class HcScrollNavContentComponent implements AfterViewInit, AfterViewChecked, OnDestroy { private readonly DEFAULT_BUFFER = 0; /** Reference to the scroll nav component. */ @Input() public nav: HcScrollNavComponent; /** If true, will force the height of the final scroll target area to be the height of the scrollable container. * This is helpful if you want the last target in the content area to be able to scroll to the top. You can alternatively * target the last item with css. *Defaults to true.* */ @Input() public makeLastTargetFullHeight = true; /** Adjust the min height of the last target */ @Input() public lastTargetMinHeightAdjustment = 0; /** Number in pixels, used to give a little leeway in the shifting of the active nav when scrolling. *Defaults to 0.* * Example: If set to 40, if showing just the bottom 40 pixels of the section before, count the next section as active. */ @Input() public bufferSpace = this.DEFAULT_BUFFER; /** If true, applies smooth scrolling via css. *Defaults to true.* */ @Input() public shouldAnimateScroll = true; /** Set to true to enable the component to change for dynamic content changes that might not be picked up by Angular */ @Input() public hasDynamicContent = false; /** Fires when a new section is scrolled into view. Broadcasts the id of that section. */ @Output() public newSectionInView: EventEmitter<string> = new EventEmitter<string>(); @ViewChild('scrollContainer', {read: CdkScrollable, static: false}) public _cdkScrollableElement: CdkScrollable; @ContentChildren(ScrollNavTargetDirective, { descendants: true }) private targets: QueryList<ScrollNavTargetDirective>; /** Id of the current section scrolled into view. */ public sectionInView: string; public get _scrollTargets(): Array<HTMLElement> { return this.targets.toArray().map(e => e.nativeElement); } private unsubscribe$ = new Subject<void>(); private minHeightForLastTargetSet = false; private systemScrollToElementId: string | undefined; private lastElementScrolledTo: HTMLElement; private systemScrollCount = 0; private dynamicInterval; private readonly SCROLL_TARGET_ATTRIBUTE = 'hcScrollTarget'; constructor(private _elementRef: ElementRef, private renderer: Renderer2) {} public ngOnDestroy(): void { this.unsubscribe$.next(); this.unsubscribe$.complete(); if (this.dynamicInterval) { clearInterval(this.dynamicInterval); } } public ngAfterViewInit(): void { setTimeout(() => { this.initializeTargets(); }, 100); if (this.hasDynamicContent) { this.refreshScrollNavTargets(); this.dynamicInterval = setInterval(() => { this.refreshScrollNavTargets(); }, 300); } // If targets are added dynamically, refresh the scrollNav this.targets.changes.pipe(takeUntil(this.unsubscribe$)).subscribe(() => { this.initializeTargets(); }); document.onclick = (event: MouseEvent) => { const element: HTMLElement | null = (event.target as HTMLElement).closest('li[hcscrolllink]'); const scrollLinkAttribute: string | null | undefined = element?.getAttribute('hcscrolllink'); if (scrollLinkAttribute) { this.systemScrollToElementId = scrollLinkAttribute; } }; } public ngAfterViewChecked(): void { if (this.makeLastTargetFullHeight && !this.minHeightForLastTargetSet) { this.insureMinHeightForLastTarget(); } } @HostListener('window:resize') _onWindowResize(): void { if (this.makeLastTargetFullHeight) { this.minHeightForLastTargetSet = false; } } /** Refresh the scroll nav targets when dynamic changes have been made. updateScrollTargetArray parameter is optional */ public refreshScrollNavTargets(updateScrollTargetArray: ScrollNavTargetDirective[] = []): void { if (updateScrollTargetArray.length > 0) { this.targets.reset(updateScrollTargetArray); this.targets.notifyOnChanges(); return; } const scrollTargetNodeList: NodeList = this._elementRef.nativeElement.querySelectorAll(`[${this.SCROLL_TARGET_ATTRIBUTE}]`); // create array to make the difference calculation off of const scrollTargetList: CombinedTargetList[] = []; scrollTargetNodeList.forEach((dynamicTarget: HTMLElement) => { scrollTargetList.push({ id: dynamicTarget.id, targetElement: dynamicTarget }); }); if (this.targets.length !== scrollTargetList.length || differenceBy(scrollTargetList, this._scrollTargets, 'id').length > 0) { const scrollTargetDirectiveArray: ScrollNavTargetDirective[] = []; scrollTargetList.forEach((dynamicTarget) => { const scrollNavTargetDirective: ScrollNavTargetDirective = new ScrollNavTargetDirective(<ElementRef>{}, this.renderer); scrollNavTargetDirective._setDirectiveToNode(dynamicTarget.targetElement); scrollTargetDirectiveArray.push(scrollNavTargetDirective); }); this.targets.reset(scrollTargetDirectiveArray); this.targets.notifyOnChanges(); } } /** Scroll to top and reset the 'automatic full height for the last item' setting. */ public refresh(): void { this.scrollToTop(); this.minHeightForLastTargetSet = false; } /** Helper function to scroll to the top of the content area. */ public scrollToTop(): void { this._cdkScrollableElement.scrollTo({top: 0}); } /** Will update the navigation state. */ public checkActiveSection(): void { if (this._scrollTargets.length > 0) { const offset: number = this._cdkScrollableElement.measureScrollOffset('top') + this._scrollTargets[0].offsetTop; this._scrollTargets.forEach((target, index) => { const el = target; let initialOffset = 0; let nextOffset = 0; if (index > 0) { initialOffset = (el as HTMLElement).offsetTop - this.bufferSpace; } if (index + 1 < this._scrollTargets.length) { const nextEl = this._scrollTargets[index + 1]; nextOffset = (nextEl as HTMLElement).offsetTop; } if ( (initialOffset && nextOffset && offset >= initialOffset && offset < nextOffset) || (initialOffset && !nextOffset && offset >= initialOffset) || (!initialOffset && nextOffset && offset < nextOffset) ) { this.lastElementScrolledTo = el as HTMLElement; this.setActiveSection((el as HTMLElement).getAttribute('id') || ''); } }); } } /** Sets the active section to passed in scrollTarget */ public setActiveSection(scrollTarget: string): void { if (this.sectionInView !== scrollTarget) { this.sectionInView = scrollTarget; this.nav._setActiveSectionById(scrollTarget); this.newSectionInView.next(scrollTarget); } } private initializeTargets(): void { if (this._cdkScrollableElement) { this._cdkScrollableElement .elementScrolled() .pipe(takeUntil(this.unsubscribe$)) .subscribe(() => { if (this.systemScrollToElementId) { this.nav.isScrolling = true; this.systemScrollCount++; setTimeout(() => { if (this.systemScrollCount > 1) { this.systemScrollCount--; } else { this.nav.isScrolling = false; this.systemScrollToElementId = undefined; this.setActiveSection(this.lastElementScrolledTo.id); this.systemScrollCount = 0; } }, 1500); } this.checkActiveSection(); }); } this._scrollTargets.forEach((target) => { if (!target.id) { throw Error('hcScrollTarget element needs an id.'); } }); this.insureMinHeightForLastTarget(); } private getTargets(targets: HTMLElement[]): HTMLElement[] { let rtnTargets: HTMLElement[] = []; targets.forEach((target) => { if (target.hasAttribute('hcScrollTarget')) { rtnTargets.push(target); } if (target.children.length > 0) { rtnTargets = rtnTargets.concat(this.getTargets(<Array<HTMLElement>>Array.from(target.children))); } }); return rtnTargets; } private insureMinHeightForLastTarget() { if (this.makeLastTargetFullHeight) { const containerHeight: number = this._cdkScrollableElement.getElementRef().nativeElement.offsetHeight; if (containerHeight && this._scrollTargets.length > 0) { this._scrollTargets.forEach((target) => { target.style.minHeight = 'unset'; }); const targetEl = this._scrollTargets[this._scrollTargets.length - 1]; targetEl.style.minHeight = `${containerHeight + this.lastTargetMinHeightAdjustment}px`; this.minHeightForLastTargetSet = true; } } } } export interface CombinedTargetList { id: string; targetElement: HTMLElement; }
the_stack
declare module 'process' { import * as tty from 'tty'; global { var process: NodeJS.Process; namespace NodeJS { // this namespace merge is here because these are specifically used // as the type for process.stdin, process.stdout, and process.stderr. // they can't live in tty.d.ts because we need to disambiguate the imported name. interface ReadStream extends tty.ReadStream {} interface WriteStream extends tty.WriteStream {} interface MemoryUsageFn { /** * The `process.memoryUsage()` method iterate over each page to gather informations about memory * usage which can be slow depending on the program memory allocations. */ (): MemoryUsage; /** * method returns an integer representing the Resident Set Size (RSS) in bytes. */ rss(): number; } interface MemoryUsage { rss: number; heapTotal: number; heapUsed: number; external: number; arrayBuffers: number; } interface CpuUsage { user: number; system: number; } interface ProcessRelease { name: string; sourceUrl?: string; headersUrl?: string; libUrl?: string; lts?: string; } interface ProcessVersions extends Dict<string> { http_parser: string; node: string; v8: string; ares: string; uv: string; zlib: string; modules: string; openssl: string; } type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; type Signals = "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; type MultipleResolveType = 'resolve' | 'reject'; type BeforeExitListener = (code: number) => void; type DisconnectListener = () => void; type ExitListener = (code: number) => void; type RejectionHandledListener = (promise: Promise<any>) => void; type UncaughtExceptionListener = (error: Error) => void; type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise<any>) => void; type WarningListener = (warning: Error) => void; type MessageListener = (message: any, sendHandle: any) => void; type SignalsListener = (signal: Signals) => void; type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; type MultipleResolveListener = (type: MultipleResolveType, promise: Promise<any>, value: any) => void; interface Socket extends ReadWriteStream { isTTY?: true; } // Alias for compatibility interface ProcessEnv extends Dict<string> {} interface HRTime { (time?: [number, number]): [number, number]; bigint(): bigint; } interface ProcessReport { /** * Directory where the report is written. * working directory of the Node.js process. * @default '' indicating that reports are written to the current */ directory: string; /** * Filename where the report is written. * The default value is the empty string. * @default '' the output filename will be comprised of a timestamp, * PID, and sequence number. */ filename: string; /** * Returns a JSON-formatted diagnostic report for the running process. * The report's JavaScript stack trace is taken from err, if present. */ getReport(err?: Error): string; /** * If true, a diagnostic report is generated on fatal errors, * such as out of memory errors or failed C++ assertions. * @default false */ reportOnFatalError: boolean; /** * If true, a diagnostic report is generated when the process * receives the signal specified by process.report.signal. * @defaul false */ reportOnSignal: boolean; /** * If true, a diagnostic report is generated on uncaught exception. * @default false */ reportOnUncaughtException: boolean; /** * The signal used to trigger the creation of a diagnostic report. * @default 'SIGUSR2' */ signal: Signals; /** * Writes a diagnostic report to a file. If filename is not provided, the default filename * includes the date, time, PID, and a sequence number. * The report's JavaScript stack trace is taken from err, if present. * * @param fileName Name of the file where the report is written. * This should be a relative path, that will be appended to the directory specified in * `process.report.directory`, or the current working directory of the Node.js process, * if unspecified. * @param error A custom error used for reporting the JavaScript stack. * @return Filename of the generated report. */ writeReport(fileName?: string): string; writeReport(error?: Error): string; writeReport(fileName?: string, err?: Error): string; } interface ResourceUsage { fsRead: number; fsWrite: number; involuntaryContextSwitches: number; ipcReceived: number; ipcSent: number; majorPageFault: number; maxRSS: number; minorPageFault: number; sharedMemorySize: number; signalsCount: number; swappedOut: number; systemCPUTime: number; unsharedDataSize: number; unsharedStackSize: number; userCPUTime: number; voluntaryContextSwitches: number; } interface EmitWarningOptions { /** * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. * * @default 'Warning' */ type?: string; /** * A unique identifier for the warning instance being emitted. */ code?: string; /** * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. * * @default process.emitWarning */ ctor?: Function; /** * Additional text to include with the error. */ detail?: string; } interface Process extends EventEmitter { /** * Can also be a tty.WriteStream, not typed due to limitations. */ stdout: WriteStream & { fd: 1; }; /** * Can also be a tty.WriteStream, not typed due to limitations. */ stderr: WriteStream & { fd: 2; }; stdin: ReadStream & { fd: 0; }; openStdin(): Socket; argv: string[]; argv0: string; execArgv: string[]; execPath: string; abort(): never; chdir(directory: string): void; cwd(): string; debugPort: number; /** * The `process.emitWarning()` method can be used to emit custom or application specific process warnings. * * These can be listened for by adding a handler to the `'warning'` event. * * @param warning The warning to emit. * @param type When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. Default: `'Warning'`. * @param code A unique identifier for the warning instance being emitted. * @param ctor When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. Default: `process.emitWarning`. */ emitWarning(warning: string | Error, ctor?: Function): void; emitWarning(warning: string | Error, type?: string, ctor?: Function): void; emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; emitWarning(warning: string | Error, options?: EmitWarningOptions): void; env: ProcessEnv; exit(code?: number): never; exitCode?: number; getgid(): number; setgid(id: number | string): void; getuid(): number; setuid(id: number | string): void; geteuid(): number; seteuid(id: number | string): void; getegid(): number; setegid(id: number | string): void; getgroups(): number[]; setgroups(groups: ReadonlyArray<string | number>): void; setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; hasUncaughtExceptionCaptureCallback(): boolean; version: string; versions: ProcessVersions; config: { target_defaults: { cflags: any[]; default_configuration: string; defines: string[]; include_dirs: string[]; libraries: string[]; }; variables: { clang: number; host_arch: string; node_install_npm: boolean; node_install_waf: boolean; node_prefix: string; node_shared_openssl: boolean; node_shared_v8: boolean; node_shared_zlib: boolean; node_use_dtrace: boolean; node_use_etw: boolean; node_use_openssl: boolean; target_arch: string; v8_no_strict_aliasing: number; v8_use_snapshot: boolean; visibility: string; }; }; kill(pid: number, signal?: string | number): true; pid: number; ppid: number; title: string; arch: string; platform: Platform; /** @deprecated since v14.0.0 - use `require.main` instead. */ mainModule?: Module; memoryUsage: MemoryUsageFn; cpuUsage(previousValue?: CpuUsage): CpuUsage; nextTick(callback: Function, ...args: any[]): void; release: ProcessRelease; features: { inspector: boolean; debug: boolean; uv: boolean; ipv6: boolean; tls_alpn: boolean; tls_sni: boolean; tls_ocsp: boolean; tls: boolean; }; /** * @deprecated since v14.0.0 - Calling process.umask() with no argument causes * the process-wide umask to be written twice. This introduces a race condition between threads, * and is a potential security vulnerability. There is no safe, cross-platform alternative API. */ umask(): number; /** * Can only be set if not in worker thread. */ umask(mask: string | number): number; uptime(): number; hrtime: HRTime; domain: Domain; // Worker send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; disconnect(): void; connected: boolean; /** * The `process.allowedNodeEnvironmentFlags` property is a special, * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] * environment variable. */ allowedNodeEnvironmentFlags: ReadonlySet<string>; /** * Only available with `--experimental-report` */ report?: ProcessReport; resourceUsage(): ResourceUsage; traceDeprecation: boolean; /* EventEmitter */ addListener(event: "beforeExit", listener: BeforeExitListener): this; addListener(event: "disconnect", listener: DisconnectListener): this; addListener(event: "exit", listener: ExitListener): this; addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; addListener(event: "warning", listener: WarningListener): this; addListener(event: "message", listener: MessageListener): this; addListener(event: Signals, listener: SignalsListener): this; addListener(event: "newListener", listener: NewListenerListener): this; addListener(event: "removeListener", listener: RemoveListenerListener): this; addListener(event: "multipleResolves", listener: MultipleResolveListener): this; emit(event: "beforeExit", code: number): boolean; emit(event: "disconnect"): boolean; emit(event: "exit", code: number): boolean; emit(event: "rejectionHandled", promise: Promise<any>): boolean; emit(event: "uncaughtException", error: Error): boolean; emit(event: "uncaughtExceptionMonitor", error: Error): boolean; emit(event: "unhandledRejection", reason: any, promise: Promise<any>): boolean; emit(event: "warning", warning: Error): boolean; emit(event: "message", message: any, sendHandle: any): this; emit(event: Signals, signal: Signals): boolean; emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; emit(event: "multipleResolves", listener: MultipleResolveListener): this; on(event: "beforeExit", listener: BeforeExitListener): this; on(event: "disconnect", listener: DisconnectListener): this; on(event: "exit", listener: ExitListener): this; on(event: "rejectionHandled", listener: RejectionHandledListener): this; on(event: "uncaughtException", listener: UncaughtExceptionListener): this; on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; on(event: "warning", listener: WarningListener): this; on(event: "message", listener: MessageListener): this; on(event: Signals, listener: SignalsListener): this; on(event: "newListener", listener: NewListenerListener): this; on(event: "removeListener", listener: RemoveListenerListener): this; on(event: "multipleResolves", listener: MultipleResolveListener): this; on(event: string | symbol, listener: (...args: any[]) => void): this; once(event: "beforeExit", listener: BeforeExitListener): this; once(event: "disconnect", listener: DisconnectListener): this; once(event: "exit", listener: ExitListener): this; once(event: "rejectionHandled", listener: RejectionHandledListener): this; once(event: "uncaughtException", listener: UncaughtExceptionListener): this; once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; once(event: "warning", listener: WarningListener): this; once(event: "message", listener: MessageListener): this; once(event: Signals, listener: SignalsListener): this; once(event: "newListener", listener: NewListenerListener): this; once(event: "removeListener", listener: RemoveListenerListener): this; once(event: "multipleResolves", listener: MultipleResolveListener): this; prependListener(event: "beforeExit", listener: BeforeExitListener): this; prependListener(event: "disconnect", listener: DisconnectListener): this; prependListener(event: "exit", listener: ExitListener): this; prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; prependListener(event: "warning", listener: WarningListener): this; prependListener(event: "message", listener: MessageListener): this; prependListener(event: Signals, listener: SignalsListener): this; prependListener(event: "newListener", listener: NewListenerListener): this; prependListener(event: "removeListener", listener: RemoveListenerListener): this; prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; prependOnceListener(event: "disconnect", listener: DisconnectListener): this; prependOnceListener(event: "exit", listener: ExitListener): this; prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; prependOnceListener(event: "warning", listener: WarningListener): this; prependOnceListener(event: "message", listener: MessageListener): this; prependOnceListener(event: Signals, listener: SignalsListener): this; prependOnceListener(event: "newListener", listener: NewListenerListener): this; prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; listeners(event: "beforeExit"): BeforeExitListener[]; listeners(event: "disconnect"): DisconnectListener[]; listeners(event: "exit"): ExitListener[]; listeners(event: "rejectionHandled"): RejectionHandledListener[]; listeners(event: "uncaughtException"): UncaughtExceptionListener[]; listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; listeners(event: "warning"): WarningListener[]; listeners(event: "message"): MessageListener[]; listeners(event: Signals): SignalsListener[]; listeners(event: "newListener"): NewListenerListener[]; listeners(event: "removeListener"): RemoveListenerListener[]; listeners(event: "multipleResolves"): MultipleResolveListener[]; } interface Global { process: Process; } } } export = process; }
the_stack
import * as nls from 'vs/nls'; import { STATUS_BAR_HOST_NAME_BACKGROUND, STATUS_BAR_HOST_NAME_FOREGROUND } from 'vs/workbench/common/theme'; import { themeColorFromId } from 'vs/platform/theme/common/themeService'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; import { Disposable, dispose } from 'vs/base/common/lifecycle'; import { MenuId, IMenuService, MenuItemAction, MenuRegistry, registerAction2, Action2, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { StatusbarAlignment, IStatusbarService, IStatusbarEntryAccessor, IStatusbarEntry } from 'vs/workbench/services/statusbar/browser/statusbar'; import { ILabelService } from 'vs/platform/label/common/label'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { Schemas } from 'vs/base/common/network'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput'; import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService'; import { PersistentConnectionEventType } from 'vs/platform/remote/common/remoteAgentConnection'; import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { isWeb } from 'vs/base/common/platform'; import { once } from 'vs/base/common/functional'; import { truncate } from 'vs/base/common/strings'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { getRemoteName } from 'vs/platform/remote/common/remoteHosts'; import { getVirtualWorkspaceLocation } from 'vs/platform/workspace/common/virtualWorkspace'; import { getCodiconAriaLabel } from 'vs/base/common/codicons'; import { ILogService } from 'vs/platform/log/common/log'; import { ReloadWindowAction } from 'vs/workbench/browser/actions/windowActions'; import { IExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IExtensionsViewPaneContainer, LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID, VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { RemoteNameContext, VirtualWorkspaceContext } from 'vs/workbench/common/contextkeys'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; import { ViewContainerLocation } from 'vs/workbench/common/views'; type ActionGroup = [string, Array<MenuItemAction | SubmenuItemAction>]; export class RemoteStatusIndicator extends Disposable implements IWorkbenchContribution { private static readonly REMOTE_ACTIONS_COMMAND_ID = 'workbench.action.remote.showMenu'; private static readonly CLOSE_REMOTE_COMMAND_ID = 'workbench.action.remote.close'; private static readonly SHOW_CLOSE_REMOTE_COMMAND_ID = !isWeb; // web does not have a "Close Remote" command private static readonly INSTALL_REMOTE_EXTENSIONS_ID = 'workbench.action.remote.extensions'; private static readonly REMOTE_STATUS_LABEL_MAX_LENGTH = 40; private remoteStatusEntry: IStatusbarEntryAccessor | undefined; private readonly legacyIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarWindowIndicatorMenu, this.contextKeyService)); // to be removed once migration completed private readonly remoteIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarRemoteIndicatorMenu, this.contextKeyService)); private remoteMenuActionsGroups: ActionGroup[] | undefined; private readonly remoteAuthority = this.environmentService.remoteAuthority; private virtualWorkspaceLocation: { scheme: string; authority: string } | undefined = undefined; private connectionState: 'initializing' | 'connected' | 'reconnecting' | 'disconnected' | undefined = undefined; private readonly connectionStateContextKey = new RawContextKey<'' | 'initializing' | 'disconnected' | 'connected'>('remoteConnectionState', '').bindTo(this.contextKeyService); private loggedInvalidGroupNames: { [group: string]: boolean } = Object.create(null); constructor( @IStatusbarService private readonly statusbarService: IStatusbarService, @IBrowserWorkbenchEnvironmentService private readonly environmentService: IBrowserWorkbenchEnvironmentService, @ILabelService private readonly labelService: ILabelService, @IContextKeyService private contextKeyService: IContextKeyService, @IMenuService private menuService: IMenuService, @IQuickInputService private readonly quickInputService: IQuickInputService, @ICommandService private readonly commandService: ICommandService, @IExtensionService private readonly extensionService: IExtensionService, @IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService, @IRemoteAuthorityResolverService private readonly remoteAuthorityResolverService: IRemoteAuthorityResolverService, @IHostService private readonly hostService: IHostService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @ILogService private readonly logService: ILogService, @IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService ) { super(); // Set initial connection state if (this.remoteAuthority) { this.connectionState = 'initializing'; this.connectionStateContextKey.set(this.connectionState); } else { this.updateVirtualWorkspaceLocation(); } this.registerActions(); this.registerListeners(); this.updateWhenInstalledExtensionsRegistered(); this.updateRemoteStatusIndicator(); } private registerActions(): void { const category = { value: nls.localize('remote.category', "Remote"), original: 'Remote' }; // Show Remote Menu const that = this; registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.REMOTE_ACTIONS_COMMAND_ID, category, title: { value: nls.localize('remote.showMenu', "Show Remote Menu"), original: 'Show Remote Menu' }, f1: true, }); } run = () => that.showRemoteMenu(); }); // Close Remote Connection if (RemoteStatusIndicator.SHOW_CLOSE_REMOTE_COMMAND_ID) { registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, category, title: { value: nls.localize('remote.close', "Close Remote Connection"), original: 'Close Remote Connection' }, f1: true, precondition: ContextKeyExpr.or(RemoteNameContext, VirtualWorkspaceContext) }); } run = () => that.hostService.openWindow({ forceReuseWindow: true, remoteAuthority: null }); }); if (this.remoteAuthority) { MenuRegistry.appendMenuItem(MenuId.MenubarFileMenu, { group: '6_close', command: { id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, title: nls.localize({ key: 'miCloseRemote', comment: ['&& denotes a mnemonic'] }, "Close Re&&mote Connection") }, order: 3.5 }); } } if (this.extensionGalleryService.isEnabled()) { registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.INSTALL_REMOTE_EXTENSIONS_ID, category, title: { value: nls.localize('remote.install', "Install Remote Development Extensions"), original: 'Install Remote Development Extensions' }, f1: true }); } run = (accessor: ServicesAccessor, input: string) => { const paneCompositeService = accessor.get(IPaneCompositePartService); return paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar, true).then(viewlet => { if (viewlet) { (viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer).search(`tag:"remote-menu"`); viewlet.focus(); } }); }; }); } } private registerListeners(): void { // Menu changes const updateRemoteActions = () => { this.remoteMenuActionsGroups = undefined; this.updateRemoteStatusIndicator(); }; this._register(this.legacyIndicatorMenu.onDidChange(updateRemoteActions)); this._register(this.remoteIndicatorMenu.onDidChange(updateRemoteActions)); // Update indicator when formatter changes as it may have an impact on the remote label this._register(this.labelService.onDidChangeFormatters(() => this.updateRemoteStatusIndicator())); // Update based on remote indicator changes if any const remoteIndicator = this.environmentService.options?.windowIndicator; if (remoteIndicator && remoteIndicator.onDidChange) { this._register(remoteIndicator.onDidChange(() => this.updateRemoteStatusIndicator())); } // Listen to changes of the connection if (this.remoteAuthority) { const connection = this.remoteAgentService.getConnection(); if (connection) { this._register(connection.onDidStateChange((e) => { switch (e.type) { case PersistentConnectionEventType.ConnectionLost: case PersistentConnectionEventType.ReconnectionRunning: case PersistentConnectionEventType.ReconnectionWait: this.setState('reconnecting'); break; case PersistentConnectionEventType.ReconnectionPermanentFailure: this.setState('disconnected'); break; case PersistentConnectionEventType.ConnectionGain: this.setState('connected'); break; } })); } } else { this._register(this.workspaceContextService.onDidChangeWorkbenchState(() => { this.updateVirtualWorkspaceLocation(); this.updateRemoteStatusIndicator(); })); } } private updateVirtualWorkspaceLocation() { this.virtualWorkspaceLocation = getVirtualWorkspaceLocation(this.workspaceContextService.getWorkspace()); } private async updateWhenInstalledExtensionsRegistered(): Promise<void> { await this.extensionService.whenInstalledExtensionsRegistered(); const remoteAuthority = this.remoteAuthority; if (remoteAuthority) { // Try to resolve the authority to figure out connection state (async () => { try { await this.remoteAuthorityResolverService.resolveAuthority(remoteAuthority); this.setState('connected'); } catch (error) { this.setState('disconnected'); } })(); } this.updateRemoteStatusIndicator(); } private setState(newState: 'disconnected' | 'connected' | 'reconnecting'): void { if (this.connectionState !== newState) { this.connectionState = newState; // simplify context key which doesn't support `connecting` if (this.connectionState === 'reconnecting') { this.connectionStateContextKey.set('disconnected'); } else { this.connectionStateContextKey.set(this.connectionState); } this.updateRemoteStatusIndicator(); } } private validatedGroup(group: string) { if (!group.match(/^(remote|virtualfs)_(\d\d)_(([a-z][a-z0-9+.-]*)_(.*))$/)) { if (!this.loggedInvalidGroupNames[group]) { this.loggedInvalidGroupNames[group] = true; this.logService.warn(`Invalid group name used in "statusBar/remoteIndicator" menu contribution: ${group}. Entries ignored. Expected format: 'remote_$ORDER_$REMOTENAME_$GROUPING or 'virtualfs_$ORDER_$FILESCHEME_$GROUPING.`); } return false; } return true; } private getRemoteMenuActions(doNotUseCache?: boolean): ActionGroup[] { if (!this.remoteMenuActionsGroups || doNotUseCache) { this.remoteMenuActionsGroups = this.remoteIndicatorMenu.getActions().filter(a => this.validatedGroup(a[0])).concat(this.legacyIndicatorMenu.getActions()); } return this.remoteMenuActionsGroups; } private updateRemoteStatusIndicator(): void { // Remote Indicator: show if provided via options, e.g. by the web embedder API const remoteIndicator = this.environmentService.options?.windowIndicator; if (remoteIndicator) { this.renderRemoteStatusIndicator(truncate(remoteIndicator.label, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH), remoteIndicator.tooltip, remoteIndicator.command); return; } // Show for remote windows on the desktop, but not when in code server web if (this.remoteAuthority && !isWeb) { const hostLabel = this.labelService.getHostLabel(Schemas.vscodeRemote, this.remoteAuthority) || this.remoteAuthority; switch (this.connectionState) { case 'initializing': this.renderRemoteStatusIndicator(nls.localize('host.open', "Opening Remote..."), nls.localize('host.open', "Opening Remote..."), undefined, true /* progress */); break; case 'reconnecting': this.renderRemoteStatusIndicator(`${nls.localize('host.reconnecting', "Reconnecting to {0}...", truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH))}`, undefined, undefined, true); break; case 'disconnected': this.renderRemoteStatusIndicator(`$(alert) ${nls.localize('disconnectedFrom', "Disconnected from {0}", truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH))}`); break; default: { const tooltip = new MarkdownString('', { isTrusted: true, supportThemeIcons: true }); const hostNameTooltip = this.labelService.getHostTooltip(Schemas.vscodeRemote, this.remoteAuthority); if (hostNameTooltip) { tooltip.appendMarkdown(hostNameTooltip); } else { tooltip.appendText(nls.localize({ key: 'host.tooltip', comment: ['{0} is a remote host name, e.g. Dev Container'] }, "Editing on {0}", hostLabel)); } this.renderRemoteStatusIndicator(`$(remote) ${truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH)}`, tooltip); } } return; } // show when in a virtual workspace if (this.virtualWorkspaceLocation) { // Workspace with label: indicate editing source const workspaceLabel = this.labelService.getHostLabel(this.virtualWorkspaceLocation.scheme, this.virtualWorkspaceLocation.authority); if (workspaceLabel) { const tooltip = new MarkdownString('', { isTrusted: true, supportThemeIcons: true }); const hostNameTooltip = this.labelService.getHostTooltip(this.virtualWorkspaceLocation.scheme, this.virtualWorkspaceLocation.authority); if (hostNameTooltip) { tooltip.appendMarkdown(hostNameTooltip); } else { tooltip.appendText(nls.localize({ key: 'workspace.tooltip', comment: ['{0} is a remote workspace name, e.g. GitHub'] }, "Editing on {0}", workspaceLabel)); } if (!isWeb || this.remoteAuthority) { tooltip.appendMarkdown('\n\n'); tooltip.appendMarkdown(nls.localize( { key: 'workspace.tooltip2', comment: ['[features are not available]({1}) is a link. Only translate `features are not available`. Do not change brackets and parentheses or {0}'] }, "Some [features are not available]({0}) for resources located on a virtual file system.", `command:${LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID}` )); } this.renderRemoteStatusIndicator(`$(remote) ${truncate(workspaceLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH)}`, tooltip); return; } } // Remote actions: offer menu if (this.getRemoteMenuActions().length > 0) { this.renderRemoteStatusIndicator(`$(remote)`, nls.localize('noHost.tooltip', "Open a Remote Window")); return; } // No Remote Extensions: hide status indicator dispose(this.remoteStatusEntry); this.remoteStatusEntry = undefined; } private renderRemoteStatusIndicator(text: string, tooltip?: string | IMarkdownString, command?: string, showProgress?: boolean): void { const name = nls.localize('remoteHost', "Remote Host"); if (typeof command !== 'string' && this.getRemoteMenuActions().length > 0) { command = RemoteStatusIndicator.REMOTE_ACTIONS_COMMAND_ID; } const ariaLabel = getCodiconAriaLabel(text); const properties: IStatusbarEntry = { name, backgroundColor: themeColorFromId(STATUS_BAR_HOST_NAME_BACKGROUND), color: themeColorFromId(STATUS_BAR_HOST_NAME_FOREGROUND), ariaLabel, text, showProgress, tooltip, command }; if (this.remoteStatusEntry) { this.remoteStatusEntry.update(properties); } else { this.remoteStatusEntry = this.statusbarService.addEntry(properties, 'status.host', StatusbarAlignment.LEFT, Number.MAX_VALUE /* first entry */); } } private showRemoteMenu() { const getCategoryLabel = (action: MenuItemAction) => { if (action.item.category) { return typeof action.item.category === 'string' ? action.item.category : action.item.category.value; } return undefined; }; const matchCurrentRemote = () => { if (this.remoteAuthority) { return new RegExp(`^remote_\\d\\d_${getRemoteName(this.remoteAuthority)}_`); } else if (this.virtualWorkspaceLocation) { return new RegExp(`^virtualfs_\\d\\d_${this.virtualWorkspaceLocation.scheme}_`); } return undefined; }; const computeItems = () => { let actionGroups = this.getRemoteMenuActions(true); const items: (IQuickPickItem | IQuickPickSeparator)[] = []; const currentRemoteMatcher = matchCurrentRemote(); if (currentRemoteMatcher) { // commands for the current remote go first actionGroups = actionGroups.sort((g1, g2) => { const isCurrentRemote1 = currentRemoteMatcher.test(g1[0]); const isCurrentRemote2 = currentRemoteMatcher.test(g2[0]); if (isCurrentRemote1 !== isCurrentRemote2) { return isCurrentRemote1 ? -1 : 1; } return g1[0].localeCompare(g2[0]); }); } let lastCategoryName: string | undefined = undefined; for (let actionGroup of actionGroups) { let hasGroupCategory = false; for (let action of actionGroup[1]) { if (action instanceof MenuItemAction) { if (!hasGroupCategory) { const category = getCategoryLabel(action); if (category !== lastCategoryName) { items.push({ type: 'separator', label: category }); lastCategoryName = category; } hasGroupCategory = true; } let label = typeof action.item.title === 'string' ? action.item.title : action.item.title.value; items.push({ type: 'item', id: action.item.id, label }); } } } items.push({ type: 'separator' }); let entriesBeforeConfig = items.length; if (RemoteStatusIndicator.SHOW_CLOSE_REMOTE_COMMAND_ID) { if (this.remoteAuthority) { items.push({ type: 'item', id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, label: nls.localize('closeRemoteConnection.title', 'Close Remote Connection') }); if (this.connectionState === 'disconnected') { items.push({ type: 'item', id: ReloadWindowAction.ID, label: nls.localize('reloadWindow', 'Reload Window') }); } } else if (this.virtualWorkspaceLocation) { items.push({ type: 'item', id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, label: nls.localize('closeVirtualWorkspace.title', 'Close Remote Workspace') }); } } if (!this.remoteAuthority && !this.virtualWorkspaceLocation && this.extensionGalleryService.isEnabled()) { items.push({ id: RemoteStatusIndicator.INSTALL_REMOTE_EXTENSIONS_ID, label: nls.localize('installRemotes', "Install Additional Remote Extensions..."), alwaysShow: true }); } if (items.length === entriesBeforeConfig) { items.pop(); // remove the separator again } return items; }; const quickPick = this.quickInputService.createQuickPick(); quickPick.items = computeItems(); quickPick.sortByLabel = false; quickPick.canSelectMany = false; once(quickPick.onDidAccept)((_ => { const selectedItems = quickPick.selectedItems; if (selectedItems.length === 1) { this.commandService.executeCommand(selectedItems[0].id!); } quickPick.hide(); })); // refresh the items when actions change const legacyItemUpdater = this.legacyIndicatorMenu.onDidChange(() => quickPick.items = computeItems()); quickPick.onDidHide(legacyItemUpdater.dispose); const itemUpdater = this.remoteIndicatorMenu.onDidChange(() => quickPick.items = computeItems()); quickPick.onDidHide(itemUpdater.dispose); quickPick.show(); } }
the_stack
import { Dialog } from "../dialogs"; import { Logger, LoggerFactory } from "../log"; import { Body, C, constructOutgoingResponse, IncomingRequestMessage, IncomingResponseMessage, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingMessageRequest, OutgoingPublishRequest, OutgoingRegisterRequest, OutgoingRequest, OutgoingRequestDelegate, OutgoingRequestMessage, OutgoingRequestMessageOptions, OutgoingResponse, OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate, ResponseOptions, URI } from "../messages"; import { InviteServerTransaction, NonInviteClientTransaction, TransactionState } from "../transactions"; import { Transport } from "../transport"; import { InviteUserAgentClient, InviteUserAgentServer, MessageUserAgentClient, MessageUserAgentServer, NotifyUserAgentServer, PublishUserAgentClient, ReferUserAgentServer, RegisterUserAgentClient, RegisterUserAgentServer, SubscribeUserAgentClient, SubscribeUserAgentServer, UserAgentClient, UserAgentServer } from "../user-agents"; import { AllowedMethods } from "./allowed-methods"; import { UserAgentCoreConfiguration } from "./user-agent-core-configuration"; import { UserAgentCoreDelegate } from "./user-agent-core-delegate"; /** * This is ported from UA.C.ACCEPTED_BODY_TYPES. * FIXME: TODO: Should be configurable/variable. */ const acceptedBodyTypes = ["application/sdp", "application/dtmf-relay"]; /** * User Agent Core. * @remarks * Core designates the functions specific to a particular type * of SIP entity, i.e., specific to either a stateful or stateless * proxy, a user agent or registrar. All cores, except those for * the stateless proxy, are transaction users. * https://tools.ietf.org/html/rfc3261#section-6 * * UAC Core: The set of processing functions required of a UAC that * reside above the transaction and transport layers. * https://tools.ietf.org/html/rfc3261#section-6 * * UAS Core: The set of processing functions required at a UAS that * resides above the transaction and transport layers. * https://tools.ietf.org/html/rfc3261#section-6 * @public */ export class UserAgentCore { /** Configuration. */ public configuration: UserAgentCoreConfiguration; /** Delegate. */ public delegate: UserAgentCoreDelegate; /** Dialogs. */ public dialogs: Map<string, Dialog>; /** Subscribers. */ public subscribers: Map<string, SubscribeUserAgentClient>; /** UACs. */ public userAgentClients = new Map<string, UserAgentClient>(); /** UASs. */ public userAgentServers = new Map<string, UserAgentServer>(); private logger: Logger; /** * Constructor. * @param configuration - Configuration. * @param delegate - Delegate. */ constructor(configuration: UserAgentCoreConfiguration, delegate: UserAgentCoreDelegate = {}) { this.configuration = configuration; this.delegate = delegate; this.dialogs = new Map<string, Dialog>(); this.subscribers = new Map<string, SubscribeUserAgentClient>(); this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); } /** Destructor. */ public dispose(): void { this.reset(); } /** Reset. */ public reset(): void { this.dialogs.forEach((dialog) => dialog.dispose()); this.dialogs.clear(); this.subscribers.forEach((subscriber) => subscriber.dispose()); this.subscribers.clear(); this.userAgentClients.forEach((uac) => uac.dispose()); this.userAgentClients.clear(); this.userAgentServers.forEach((uac) => uac.dispose()); this.userAgentServers.clear(); } /** Logger factory. */ get loggerFactory(): LoggerFactory { return this.configuration.loggerFactory; } /** Transport. */ get transport(): Transport { const transport = this.configuration.transportAccessor(); if (!transport) { throw new Error("Transport undefined."); } return transport; } /** * Send INVITE. * @param request - Outgoing request. * @param delegate - Request delegate. */ public invite(request: OutgoingRequestMessage, delegate?: OutgoingInviteRequestDelegate): OutgoingInviteRequest { return new InviteUserAgentClient(this, request, delegate); } /** * Send MESSAGE. * @param request - Outgoing request. * @param delegate - Request delegate. */ public message(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingMessageRequest { return new MessageUserAgentClient(this, request, delegate); } /** * Send PUBLISH. * @param request - Outgoing request. * @param delegate - Request delegate. */ public publish(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingPublishRequest { return new PublishUserAgentClient(this, request, delegate); } /** * Send REGISTER. * @param request - Outgoing request. * @param delegate - Request delegate. */ public register(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingRegisterRequest { return new RegisterUserAgentClient(this, request, delegate); } /** * Send SUBSCRIBE. * @param request - Outgoing request. * @param delegate - Request delegate. */ public subscribe( request: OutgoingRequestMessage, delegate?: OutgoingSubscribeRequestDelegate ): OutgoingSubscribeRequest { return new SubscribeUserAgentClient(this, request, delegate); } /** * Send a request. * @param request - Outgoing request. * @param delegate - Request delegate. */ public request(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingRequest { return new UserAgentClient(NonInviteClientTransaction, this, request, delegate); } /** * Outgoing request message factory function. * @param method - Method. * @param requestURI - Request-URI. * @param fromURI - From URI. * @param toURI - To URI. * @param options - Request options. * @param extraHeaders - Extra headers to add. * @param body - Message body. */ public makeOutgoingRequestMessage( method: string, requestURI: URI, fromURI: URI, toURI: URI, options: OutgoingRequestMessageOptions, extraHeaders?: Array<string>, body?: Body ): OutgoingRequestMessage { // default values from user agent configuration const callIdPrefix = this.configuration.sipjsId; const fromDisplayName = this.configuration.displayName; const forceRport = this.configuration.viaForceRport; const hackViaTcp = this.configuration.hackViaTcp; const optionTags = this.configuration.supportedOptionTags.slice(); if (method === C.REGISTER) { optionTags.push("path", "gruu"); } if (method === C.INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { optionTags.push("gruu"); } const routeSet = this.configuration.routeSet; const userAgentString = this.configuration.userAgentHeaderFieldValue; const viaHost = this.configuration.viaHost; const defaultOptions: OutgoingRequestMessageOptions = { callIdPrefix, forceRport, fromDisplayName, hackViaTcp, optionTags, routeSet, userAgentString, viaHost }; // merge provided options with default options const requestOptions: OutgoingRequestMessageOptions = { ...defaultOptions, ...options }; return new OutgoingRequestMessage(method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); } /** * Handle an incoming request message from the transport. * @param message - Incoming request message from transport layer. */ public receiveIncomingRequestFromTransport(message: IncomingRequestMessage): void { this.receiveRequestFromTransport(message); } /** * Handle an incoming response message from the transport. * @param message - Incoming response message from transport layer. */ public receiveIncomingResponseFromTransport(message: IncomingResponseMessage): void { this.receiveResponseFromTransport(message); } /** * A stateless UAS is a UAS that does not maintain transaction state. * It replies to requests normally, but discards any state that would * ordinarily be retained by a UAS after a response has been sent. If a * stateless UAS receives a retransmission of a request, it regenerates * the response and re-sends it, just as if it were replying to the first * instance of the request. A UAS cannot be stateless unless the request * processing for that method would always result in the same response * if the requests are identical. This rules out stateless registrars, * for example. Stateless UASs do not use a transaction layer; they * receive requests directly from the transport layer and send responses * directly to the transport layer. * https://tools.ietf.org/html/rfc3261#section-8.2.7 * @param message - Incoming request message to reply to. * @param statusCode - Status code to reply with. */ public replyStateless(message: IncomingRequestMessage, options: ResponseOptions): OutgoingResponse { const userAgent = this.configuration.userAgentHeaderFieldValue; const supported = this.configuration.supportedOptionTagsResponse; options = { ...options, userAgent, supported }; const response = constructOutgoingResponse(message, options); this.transport.send(response.message).catch((error) => { // If the transport rejects, it SHOULD reject with a TransportError. // But the transport may be external code, so we are careful... if (error instanceof Error) { this.logger.error(error.message); } this.logger.error(`Transport error occurred sending stateless reply to ${message.method} request.`); // TODO: Currently there is no hook to provide notification that a transport error occurred // and throwing would result in an uncaught error (in promise), so we silently eat the error. // Furthermore, silently eating stateless reply transport errors is arguably what we want to do here. }); return response; } /** * In Section 18.2.1, replace the last paragraph with: * * Next, the server transport attempts to match the request to a * server transaction. It does so using the matching rules described * in Section 17.2.3. If a matching server transaction is found, the * request is passed to that transaction for processing. If no match * is found, the request is passed to the core, which may decide to * construct a new server transaction for that request. * https://tools.ietf.org/html/rfc6026#section-8.10 * @param message - Incoming request message from transport layer. */ private receiveRequestFromTransport(message: IncomingRequestMessage): void { // When a request is received from the network by the server, it has to // be matched to an existing transaction. This is accomplished in the // following manner. // // The branch parameter in the topmost Via header field of the request // is examined. If it is present and begins with the magic cookie // "z9hG4bK", the request was generated by a client transaction // compliant to this specification. Therefore, the branch parameter // will be unique across all transactions sent by that client. The // request matches a transaction if: // // 1. the branch parameter in the request is equal to the one in the // top Via header field of the request that created the // transaction, and // // 2. the sent-by value in the top Via of the request is equal to the // one in the request that created the transaction, and // // 3. the method of the request matches the one that created the // transaction, except for ACK, where the method of the request // that created the transaction is INVITE. // // This matching rule applies to both INVITE and non-INVITE transactions // alike. // // The sent-by value is used as part of the matching process because // there could be accidental or malicious duplication of branch // parameters from different clients. // https://tools.ietf.org/html/rfc3261#section-17.2.3 const transactionId = message.viaBranch; // FIXME: Currently only using rule 1... const uas = this.userAgentServers.get(transactionId); // When receiving an ACK that matches an existing INVITE server // transaction and that does not contain a branch parameter containing // the magic cookie defined in RFC 3261, the matching transaction MUST // be checked to see if it is in the "Accepted" state. If it is, then // the ACK must be passed directly to the transaction user instead of // being absorbed by the transaction state machine. This is necessary // as requests from RFC 2543 clients will not include a unique branch // parameter, and the mechanisms for calculating the transaction ID from // such a request will be the same for both INVITE and ACKs. // https://tools.ietf.org/html/rfc6026#section-6 // Any ACKs received from the network while in the "Accepted" state MUST be // passed directly to the TU and not absorbed. // https://tools.ietf.org/html/rfc6026#section-7.1 if (message.method === C.ACK) { if (uas && uas.transaction.state === TransactionState.Accepted) { if (uas instanceof InviteUserAgentServer) { // These are ACKs matching an INVITE server transaction. // These should never happen with RFC 3261 compliant user agents // (would be a broken ACK to negative final response or something) // but is apparently how RFC 2543 user agents do things. // We are not currently supporting this case. // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${transactionId}.`); return; } } } // The CANCEL method requests that the TU at the server side cancel a // pending transaction. The TU determines the transaction to be // cancelled by taking the CANCEL request, and then assuming that the // request method is anything but CANCEL or ACK and applying the // transaction matching procedures of Section 17.2.3. The matching // transaction is the one to be cancelled. // https://tools.ietf.org/html/rfc3261#section-9.2 if (message.method === C.CANCEL) { if (uas) { // Regardless of the method of the original request, as long as the // CANCEL matched an existing transaction, the UAS answers the CANCEL // request itself with a 200 (OK) response. // https://tools.ietf.org/html/rfc3261#section-9.2 this.replyStateless(message, { statusCode: 200 }); // If the transaction for the original request still exists, the behavior // of the UAS on receiving a CANCEL request depends on whether it has already // sent a final response for the original request. If it has, the CANCEL // request has no effect on the processing of the original request, no // effect on any session state, and no effect on the responses generated // for the original request. If the UAS has not issued a final response // for the original request, its behavior depends on the method of the // original request. If the original request was an INVITE, the UAS // SHOULD immediately respond to the INVITE with a 487 (Request // Terminated). // https://tools.ietf.org/html/rfc3261#section-9.2 if ( uas.transaction instanceof InviteServerTransaction && uas.transaction.state === TransactionState.Proceeding ) { if (uas instanceof InviteUserAgentServer) { uas.receiveCancel(message); } // A CANCEL request has no impact on the processing of // transactions with any other method defined in this specification. // https://tools.ietf.org/html/rfc3261#section-9.2 } } else { // If the UAS did not find a matching transaction for the CANCEL // according to the procedure above, it SHOULD respond to the CANCEL // with a 481 (Call Leg/Transaction Does Not Exist). // https://tools.ietf.org/html/rfc3261#section-9.2 this.replyStateless(message, { statusCode: 481 }); } return; } // If a matching server transaction is found, the request is passed to that // transaction for processing. // https://tools.ietf.org/html/rfc6026#section-8.10 if (uas) { uas.transaction.receiveRequest(message); return; } // If no match is found, the request is passed to the core, which may decide to // construct a new server transaction for that request. // https://tools.ietf.org/html/rfc6026#section-8.10 this.receiveRequest(message); return; } /** * UAC and UAS procedures depend strongly on two factors. First, based * on whether the request or response is inside or outside of a dialog, * and second, based on the method of a request. Dialogs are discussed * thoroughly in Section 12; they represent a peer-to-peer relationship * between user agents and are established by specific SIP methods, such * as INVITE. * @param message - Incoming request message. */ private receiveRequest(message: IncomingRequestMessage): void { // 8.2 UAS Behavior // UASs SHOULD process the requests in the order of the steps that // follow in this section (that is, starting with authentication, then // inspecting the method, the header fields, and so on throughout the // remainder of this section). // https://tools.ietf.org/html/rfc3261#section-8.2 // 8.2.1 Method Inspection // Once a request is authenticated (or authentication is skipped), the // UAS MUST inspect the method of the request. If the UAS recognizes // but does not support the method of a request, it MUST generate a 405 // (Method Not Allowed) response. Procedures for generating responses // are described in Section 8.2.6. The UAS MUST also add an Allow // header field to the 405 (Method Not Allowed) response. The Allow // header field MUST list the set of methods supported by the UAS // generating the message. // https://tools.ietf.org/html/rfc3261#section-8.2.1 if (!AllowedMethods.includes(message.method)) { const allowHeader = "Allow: " + AllowedMethods.toString(); this.replyStateless(message, { statusCode: 405, extraHeaders: [allowHeader] }); return; } // 8.2.2 Header Inspection // https://tools.ietf.org/html/rfc3261#section-8.2.2 if (!message.ruri) { // FIXME: A request message should always have an ruri throw new Error("Request-URI undefined."); } // 8.2.2.1 To and Request-URI // If the Request-URI uses a scheme not supported by the UAS, it SHOULD // reject the request with a 416 (Unsupported URI Scheme) response. // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 if (message.ruri.scheme !== "sip") { this.replyStateless(message, { statusCode: 416 }); return; } // 8.2.2.1 To and Request-URI // If the Request-URI does not identify an address that the // UAS is willing to accept requests for, it SHOULD reject // the request with a 404 (Not Found) response. // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 const ruri = message.ruri; const ruriMatches = (uri: URI | undefined): boolean => { return !!uri && uri.user === ruri.user; }; if ( !ruriMatches(this.configuration.aor) && !( ruriMatches(this.configuration.contact.uri) || ruriMatches(this.configuration.contact.pubGruu) || ruriMatches(this.configuration.contact.tempGruu) ) ) { this.logger.warn("Request-URI does not point to us."); if (message.method !== C.ACK) { this.replyStateless(message, { statusCode: 404 }); } return; } // 8.2.2.1 To and Request-URI // Other potential sources of received Request-URIs include // the Contact header fields of requests and responses sent by the UA // that establish or refresh dialogs. // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 if (message.method === C.INVITE) { if (!message.hasHeader("Contact")) { this.replyStateless(message, { statusCode: 400, reasonPhrase: "Missing Contact Header" }); return; } } // 8.2.2.2 Merged Requests // If the request has no tag in the To header field, the UAS core MUST // check the request against ongoing transactions. If the From tag, // Call-ID, and CSeq exactly match those associated with an ongoing // transaction, but the request does not match that transaction (based // on the matching rules in Section 17.2.3), the UAS core SHOULD // generate a 482 (Loop Detected) response and pass it to the server // transaction. // // The same request has arrived at the UAS more than once, following // different paths, most likely due to forking. The UAS processes // the first such request received and responds with a 482 (Loop // Detected) to the rest of them. // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 if (!message.toTag) { const transactionId = message.viaBranch; if (!this.userAgentServers.has(transactionId)) { const mergedRequest = Array.from(this.userAgentServers.values()).some( (uas) => uas.transaction.request.fromTag === message.fromTag && uas.transaction.request.callId === message.callId && uas.transaction.request.cseq === message.cseq ); if (mergedRequest) { this.replyStateless(message, { statusCode: 482 }); return; } } } // 8.2.2.3 Require // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 // TODO // 8.2.3 Content Processing // https://tools.ietf.org/html/rfc3261#section-8.2.3 // TODO // 8.2.4 Applying Extensions // https://tools.ietf.org/html/rfc3261#section-8.2.4 // TODO // 8.2.5 Processing the Request // Assuming all of the checks in the previous subsections are passed, // the UAS processing becomes method-specific. // https://tools.ietf.org/html/rfc3261#section-8.2.5 // The UAS will receive the request from the transaction layer. If the // request has a tag in the To header field, the UAS core computes the // dialog identifier corresponding to the request and compares it with // existing dialogs. If there is a match, this is a mid-dialog request. // In that case, the UAS first applies the same processing rules for // requests outside of a dialog, discussed in Section 8.2. // https://tools.ietf.org/html/rfc3261#section-12.2.2 if (message.toTag) { this.receiveInsideDialogRequest(message); } else { this.receiveOutsideDialogRequest(message); } return; } /** * Once a dialog has been established between two UAs, either of them * MAY initiate new transactions as needed within the dialog. The UA * sending the request will take the UAC role for the transaction. The * UA receiving the request will take the UAS role. Note that these may * be different roles than the UAs held during the transaction that * established the dialog. * https://tools.ietf.org/html/rfc3261#section-12.2 * @param message - Incoming request message. */ private receiveInsideDialogRequest(message: IncomingRequestMessage): void { // NOTIFY requests are matched to such SUBSCRIBE requests if they // contain the same "Call-ID", a "To" header field "tag" parameter that // matches the "From" header field "tag" parameter of the SUBSCRIBE // request, and the same "Event" header field. Rules for comparisons of // the "Event" header fields are described in Section 8.2.1. // https://tools.ietf.org/html/rfc6665#section-4.4.1 if (message.method === C.NOTIFY) { const event = message.parseHeader("Event"); if (!event || !event.event) { this.replyStateless(message, { statusCode: 489 }); return; } // FIXME: Subscriber id should also matching on event id. const subscriberId = message.callId + message.toTag + event.event; const subscriber = this.subscribers.get(subscriberId); if (subscriber) { const uas = new NotifyUserAgentServer(this, message); subscriber.onNotify(uas); return; } } // Requests sent within a dialog, as any other requests, are atomic. If // a particular request is accepted by the UAS, all the state changes // associated with it are performed. If the request is rejected, none // of the state changes are performed. // // Note that some requests, such as INVITEs, affect several pieces of // state. // // The UAS will receive the request from the transaction layer. If the // request has a tag in the To header field, the UAS core computes the // dialog identifier corresponding to the request and compares it with // existing dialogs. If there is a match, this is a mid-dialog request. // https://tools.ietf.org/html/rfc3261#section-12.2.2 const dialogId = message.callId + message.toTag + message.fromTag; const dialog = this.dialogs.get(dialogId); if (dialog) { // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS // You got the question right. // // And you got the right answer too. :-) // // Thanks, // Paul // // Robert Sparks wrote: // > So I've lost track of the question during the musing. // > // > I _think_ the fundamental question being asked is this: // > // > Is an endpoint required to reject (with a 481) an OPTIONS request that // > arrives with at to-tag but does not match any existing dialog state. // > (Assuming some earlier requirement hasn't forced another error code). Or // > is it OK if it just sends // > a 200 OK anyhow. // > // > My take on the collection of specs is that its _not_ ok for it to send // > the 200 OK anyhow and that it is required to send // > the 481. I base this primarily on these sentences from 11.2 in 3261: // > // > The response to an OPTIONS is constructed using the standard rules // > for a SIP response as discussed in Section 8.2.6. The response code // > chosen MUST be the same that would have been chosen had the request // > been an INVITE. // > // > Did I miss the point of the question? // > // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: // > // >> [Including Robert in hopes of getting his insight on this.] // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html // // Requests that do not change in any way the state of a dialog may be // received within a dialog (for example, an OPTIONS request). They are // processed as if they had been received outside the dialog. // https://tools.ietf.org/html/rfc3261#section-12.2.2 if (message.method === C.OPTIONS) { const allowHeader = "Allow: " + AllowedMethods.toString(); const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); this.replyStateless(message, { statusCode: 200, extraHeaders: [allowHeader, acceptHeader] }); return; } // Pass the incoming request to the dialog for further handling. dialog.receiveRequest(message); return; } // The most important behaviors of a stateless UAS are the following: // ... // o A stateless UAS MUST ignore ACK requests. // ... // https://tools.ietf.org/html/rfc3261#section-8.2.7 if (message.method === C.ACK) { // If a final response to an INVITE was sent statelessly, // the corresponding ACK: // - will not match an existing transaction // - may have tag in the To header field // - not not match any existing dialogs // Absorb unmatched ACKs. return; } // If the request has a tag in the To header field, but the dialog // identifier does not match any existing dialogs, the UAS may have // crashed and restarted, or it may have received a request for a // different (possibly failed) UAS (the UASs can construct the To tags // so that a UAS can identify that the tag was for a UAS for which it is // providing recovery). Another possibility is that the incoming // request has been simply mis-routed. Based on the To tag, the UAS MAY // either accept or reject the request. Accepting the request for // acceptable To tags provides robustness, so that dialogs can persist // even through crashes. UAs wishing to support this capability must // take into consideration some issues such as choosing monotonically // increasing CSeq sequence numbers even across reboots, reconstructing // the route set, and accepting out-of-range RTP timestamps and sequence // numbers. // // If the UAS wishes to reject the request because it does not wish to // recreate the dialog, it MUST respond to the request with a 481 // (Call/Transaction Does Not Exist) status code and pass that to the // server transaction. // https://tools.ietf.org/html/rfc3261#section-12.2.2 this.replyStateless(message, { statusCode: 481 }); return; } /** * Assuming all of the checks in the previous subsections are passed, * the UAS processing becomes method-specific. * https://tools.ietf.org/html/rfc3261#section-8.2.5 * @param message - Incoming request message. */ private receiveOutsideDialogRequest(message: IncomingRequestMessage): void { switch (message.method) { case C.ACK: // Absorb stray out of dialog ACKs break; case C.BYE: // If the BYE does not match an existing dialog, the UAS core SHOULD // generate a 481 (Call/Transaction Does Not Exist) response and pass // that to the server transaction. This rule means that a BYE sent // without tags by a UAC will be rejected. // https://tools.ietf.org/html/rfc3261#section-15.1.2 this.replyStateless(message, { statusCode: 481 }); break; case C.CANCEL: throw new Error(`Unexpected out of dialog request method ${message.method}.`); break; case C.INFO: // Use of the INFO method does not constitute a separate dialog usage. // INFO messages are always part of, and share the fate of, an invite // dialog usage [RFC5057]. INFO messages cannot be sent as part of // other dialog usages, or outside an existing dialog. // https://tools.ietf.org/html/rfc6086#section-1 this.replyStateless(message, { statusCode: 405 }); // Should never happen break; case C.INVITE: // https://tools.ietf.org/html/rfc3261#section-13.3.1 { const uas = new InviteUserAgentServer(this, message); this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject(); } break; case C.MESSAGE: // MESSAGE requests are discouraged inside a dialog. Implementations // are restricted from creating a usage for the purpose of carrying a // sequence of MESSAGE requests (though some implementations use it that // way, against the standard recommendation). // https://tools.ietf.org/html/rfc5057#section-5.3 { const uas = new MessageUserAgentServer(this, message); this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); } break; case C.NOTIFY: // Obsoleted by: RFC 6665 // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, // it is the responsibility of the parties defining those mechanisms to // ensure that correlation of a NOTIFY message to the corresponding // subscription is possible. Designers of such mechanisms are also // warned to make a distinction between sending a NOTIFY message to a // subscriber who is aware of the subscription, and sending a NOTIFY // message to an unsuspecting node. The latter behavior is invalid, and // MUST receive a "481 Subscription does not exist" response (unless // some other 400- or 500-class error code is more applicable), as // described in section 3.2.4. In other words, knowledge of a // subscription must exist in both the subscriber and the notifier to be // valid, even if installed via a non-SUBSCRIBE mechanism. // https://tools.ietf.org/html/rfc3265#section-3.2 // // NOTIFY requests are sent to inform subscribers of changes in state to // which the subscriber has a subscription. Subscriptions are created // using the SUBSCRIBE method. In legacy implementations, it is // possible that other means of subscription creation have been used. // However, this specification does not allow the creation of // subscriptions except through SUBSCRIBE requests and (for backwards- // compatibility) REFER requests [RFC3515]. // https://tools.ietf.org/html/rfc6665#section-3.2 { const uas = new NotifyUserAgentServer(this, message); this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.reject({ statusCode: 405 }); } break; case C.OPTIONS: // https://tools.ietf.org/html/rfc3261#section-11.2 { const allowHeader = "Allow: " + AllowedMethods.toString(); const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); this.replyStateless(message, { statusCode: 200, extraHeaders: [allowHeader, acceptHeader] }); } break; case C.REFER: // https://tools.ietf.org/html/rfc3515#section-2.4.2 { const uas = new ReferUserAgentServer(this, message); this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject({ statusCode: 405 }); } break; case C.REGISTER: // https://tools.ietf.org/html/rfc3261#section-10.3 { const uas = new RegisterUserAgentServer(this, message); this.delegate.onRegister ? this.delegate.onRegister(uas) : uas.reject({ statusCode: 405 }); } break; case C.SUBSCRIBE: // https://tools.ietf.org/html/rfc6665#section-4.2 { const uas = new SubscribeUserAgentServer(this, message); this.delegate.onSubscribe ? this.delegate.onSubscribe(uas) : uas.reject({ statusCode: 480 }); } break; default: throw new Error(`Unexpected out of dialog request method ${message.method}.`); } return; } /** * Responses are first processed by the transport layer and then passed * up to the transaction layer. The transaction layer performs its * processing and then passes the response up to the TU. The majority * of response processing in the TU is method specific. However, there * are some general behaviors independent of the method. * https://tools.ietf.org/html/rfc3261#section-8.1.3 * @param message - Incoming response message from transport layer. */ private receiveResponseFromTransport(message: IncomingResponseMessage): void { // 8.1.3.1 Transaction Layer Errors // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 // Handled by transaction layer callbacks. // 8.1.3.2 Unrecognized Responses // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 // TODO // 8.1.3.3 Vias // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 if (message.getHeaders("via").length > 1) { this.logger.warn("More than one Via header field present in the response, dropping"); return; } // 8.1.3.4 Processing 3xx Responses // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 // TODO // 8.1.3.5 Processing 4xx Responses // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 // TODO // When the transport layer in the client receives a response, it has to // determine which client transaction will handle the response, so that // the processing of Sections 17.1.1 and 17.1.2 can take place. The // branch parameter in the top Via header field is used for this // purpose. A response matches a client transaction under two // conditions: // // 1. If the response has the same value of the branch parameter in // the top Via header field as the branch parameter in the top // Via header field of the request that created the transaction. // // 2. If the method parameter in the CSeq header field matches the // method of the request that created the transaction. The // method is needed since a CANCEL request constitutes a // different transaction, but shares the same value of the branch // parameter. // https://tools.ietf.org/html/rfc3261#section-17.1.3 const userAgentClientId = message.viaBranch + message.method; const userAgentClient = this.userAgentClients.get(userAgentClientId); // The client transport uses the matching procedures of Section // 17.1.3 to attempt to match the response to an existing // transaction. If there is a match, the response MUST be passed to // that transaction. Otherwise, any element other than a stateless // proxy MUST silently discard the response. // https://tools.ietf.org/html/rfc6026#section-8.9 if (userAgentClient) { userAgentClient.transaction.receiveResponse(message); } else { this.logger.warn( `Discarding unmatched ${message.statusCode} response to ${message.method} ${userAgentClientId}.` ); } } }
the_stack
import { Event, Options, Status, Response } from '@amplitude/types'; import { BASE_RETRY_TIMEOUT_DEPRECATED, BASE_RETRY_TIMEOUT_DEPRECATED_WARNING } from '../constants'; import { asyncSleep, collectInvalidEventIndices, logger } from '@amplitude/utils'; import { BaseRetryHandler } from './baseRetry'; interface RetryMetadata { shouldRetry: boolean; shouldReduceEventCount: boolean; eventIndicesToRemove: number[]; response: Response; } /** * Converts deprecated maxRetries option to retryTimeouts */ function convertMaxRetries(maxRetries: number): number[] { const retryTimeouts = []; let currentTimeout = BASE_RETRY_TIMEOUT_DEPRECATED; for (let i = 0; i < maxRetries; i++) { retryTimeouts.push(currentTimeout); currentTimeout *= 2; } return retryTimeouts; } function isNodeError(err: Error & NodeJS.ErrnoException): boolean { return err.code !== undefined && err.errno !== undefined && err.syscall !== undefined; } export class RetryHandler extends BaseRetryHandler { // A map of maps to event buffers for failed events // The first key is userId (or ''), and second is deviceId (or '') private readonly _idToBuffer: Map<string, Map<string, Event[]>> = new Map<string, Map<string, Event[]>>(); private _eventsInRetry = 0; public constructor(apiKey: string, options: Partial<Options> = {}) { super(apiKey, options); if (this._options.maxRetries !== undefined) { logger.warn(BASE_RETRY_TIMEOUT_DEPRECATED_WARNING); this._options.retryTimeouts = convertMaxRetries(this._options.maxRetries); delete this._options.maxRetries; } } /** * @inheritDoc */ public async sendEventsWithRetry(events: readonly Event[]): Promise<Response> { let response: Response = { status: Status.Unknown, statusCode: 0 }; let eventsToSend: Event[] = []; try { eventsToSend = this._pruneEvents(events); response = await this._transport.sendPayload(this._getPayload(eventsToSend)); if (response.status !== Status.Success) { throw new Error(response.status); } } catch (err) { if (isNodeError(err)) { response = { status: Status.SystemError, statusCode: 0, error: err, }; } else { logger.warn('Unknown error caught when sending events'); logger.warn(err); } if (this._shouldRetryEvents()) { this._onEventsError(eventsToSend, response); } } return response; } private _shouldRetryEvents(): boolean { if (this._options.retryTimeouts.length === 0) { return false; } // TODO: Refine logic of what happens when we reach the queue limit. return this._eventsInRetry < this._options.maxCachedEvents; } // Sends events with ids currently in active retry buffers straight // to the retry buffer they should be in private _pruneEvents(events: readonly Event[]): Event[] { const prunedEvents: Event[] = []; if (Array.isArray(events)) { for (const event of events) { const { user_id: userId = '', device_id: deviceId = '' } = event; // We can ignore events with neither. They would fail anyways when sent as event. if (userId.length > 0 || deviceId.length > 0) { const retryBuffer = this._getRetryBuffer(userId, deviceId); if (retryBuffer !== null) { retryBuffer.push(event); this._eventsInRetry++; } else { prunedEvents.push(event); } } } } return prunedEvents; } private _getRetryBuffer(userId: string, deviceId: string): Event[] | null { const deviceToBufferMap = this._idToBuffer.get(userId); if (deviceToBufferMap === undefined) { return null; } return deviceToBufferMap.get(deviceId) ?? null; } // cleans up the id to buffer map if the job is done private _cleanUpBuffer(userId: string, deviceId: string): void { const deviceToBufferMap = this._idToBuffer.get(userId); if (deviceToBufferMap === undefined) { return; } const eventsToRetry = deviceToBufferMap.get(deviceId); if (eventsToRetry !== undefined && eventsToRetry.length === 0) { deviceToBufferMap.delete(deviceId); } if (deviceToBufferMap.size === 0) { this._idToBuffer.delete(userId); } } private _onEventsError(events: readonly Event[], response: Response): void { let eventsToRetry: readonly Event[] = events; // See if there are any events we can immediately throw out if (response.status === Status.RateLimit && response.body !== undefined) { const { exceededDailyQuotaUsers, exceededDailyQuotaDevices } = response.body; eventsToRetry = events.filter(({ user_id: userId, device_id: deviceId }) => { return ( !(userId !== undefined && userId in exceededDailyQuotaUsers) && !(deviceId !== undefined && deviceId in exceededDailyQuotaDevices) ); }); } else if (response.status === Status.Invalid) { if (typeof response.body?.missingField === 'string' || events.length === 1) { // Return early if there's an issue with the entire payload // or if there's only one event and its invalid return; } else if (response.body !== undefined) { const invalidEventIndices = new Set<number>(collectInvalidEventIndices(response)); eventsToRetry = events.filter((_, index) => !invalidEventIndices.has(index)); } } else if (response.status === Status.Success) { // In case _onEventsError was called when we were actually successful // In which case, why even start retrying events? return; } eventsToRetry.forEach((event: Event) => { const { user_id: userId = '', device_id: deviceId = '' } = event; if (userId.length > 0 || deviceId.length > 0) { let deviceToBufferMap = this._idToBuffer.get(userId); if (deviceToBufferMap === undefined) { deviceToBufferMap = new Map<string, Event[]>(); this._idToBuffer.set(userId, deviceToBufferMap); } let retryBuffer = deviceToBufferMap.get(deviceId); if (retryBuffer === undefined) { retryBuffer = []; deviceToBufferMap.set(deviceId, retryBuffer); // In the next event loop, start retrying these events setTimeout(() => { // eslint-disable-next-line @typescript-eslint/no-floating-promises this._retryEventsOnLoop(userId, deviceId); }, 0); } this._eventsInRetry++; retryBuffer.push(event); } }); } private async _retryEventsOnce( userId: string, deviceId: string, eventsToRetry: readonly Event[], ): Promise<RetryMetadata> { const response = await this._transport.sendPayload(this._getPayload(eventsToRetry)); let shouldRetry = true; let shouldReduceEventCount = false; let eventIndicesToRemove: number[] = []; if (response.status === Status.RateLimit) { // RateLimit: See if we hit the daily quota if (response.body !== undefined) { const { exceededDailyQuotaUsers, exceededDailyQuotaDevices } = response.body; if (deviceId in exceededDailyQuotaDevices || userId in exceededDailyQuotaUsers) { shouldRetry = false; // This device/user may not be retried for a while. Just give up. } } shouldReduceEventCount = true; // Reduce the payload to reduce risk of throttling } else if (response.status === Status.PayloadTooLarge) { shouldReduceEventCount = true; } else if (response.status === Status.Invalid) { if (eventsToRetry.length === 1) { shouldRetry = false; // If there's only one event, just toss it. } else { eventIndicesToRemove = collectInvalidEventIndices(response); // Figure out which events need to go. } } else if (response.status === Status.Success) { // Success! We sent the events shouldRetry = false; // End the retry loop } return { shouldRetry, shouldReduceEventCount, eventIndicesToRemove, response }; } private async _retryEventsOnLoop(userId: string, deviceId: string): Promise<void> { const eventsBuffer = this._getRetryBuffer(userId, deviceId); if (eventsBuffer === null || eventsBuffer.length === 0) { this._cleanUpBuffer(userId, deviceId); return; } let eventCount = eventsBuffer.length; for (let numRetries = 0; numRetries < this._options.retryTimeouts.length; numRetries++) { const sleepDuration = this._options.retryTimeouts[numRetries]; await asyncSleep(sleepDuration); const isLastTry = numRetries === this._options.retryTimeouts.length; const eventsToRetry = eventsBuffer.slice(0, eventCount); const { shouldRetry, shouldReduceEventCount, eventIndicesToRemove, response } = await this._retryEventsOnce( userId, deviceId, eventsToRetry, ); if (this._options.onRetry !== null) this._options.onRetry(response, numRetries, numRetries === this._options.retryTimeouts.length - 1); if (eventIndicesToRemove.length > 0) { let numEventsRemoved = 0; // Reverse the indices so that splicing doesn't cause any indexing issues. Array.from(eventIndicesToRemove) .reverse() .forEach(index => { if (index < eventCount) { eventsBuffer.splice(index, 1); numEventsRemoved += 1; } }); eventCount -= numEventsRemoved; this._eventsInRetry -= eventCount; if (eventCount < 1) { break; // If we managed to remove all the events, break off early. } } if (!shouldRetry) { break; // We ended! } if (shouldReduceEventCount && !isLastTry) { eventCount = Math.max(eventCount >> 1, 1); } } // Clean up the events // Either because they were sent, or because we decided to no longer try them eventsBuffer.splice(0, eventCount); this._eventsInRetry -= eventCount; // if more events came in during this time, // retry them on a new loop // otherwise, this call will immediately return on the next event loop. setTimeout(() => { // eslint-disable-next-line @typescript-eslint/no-floating-promises this._retryEventsOnLoop(userId, deviceId); }, 0); } }
the_stack
import * as cdk from '@aws-cdk/core'; import * as sns from '@aws-cdk/aws-sns'; import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; import * as cw_actions from '@aws-cdk/aws-cloudwatch-actions'; import * as codebuild from '@aws-cdk/aws-codebuild'; import * as iam from '@aws-cdk/aws-iam'; import * as events from '@aws-cdk/aws-events'; import * as targets from '@aws-cdk/aws-events-targets'; import * as lambda from '@aws-cdk/aws-lambda'; import * as lambda_nodejs from '@aws-cdk/aws-lambda-nodejs'; import * as path from 'path'; import * as route53 from '@aws-cdk/aws-route53'; export interface CertificateProps extends cdk.NestedStackProps { readonly notifyTopic: sns.ITopic; readonly domainName: string; readonly hostedZone: route53.IHostedZone; readonly contactEmail: string; readonly distributionId: string; } export class CertificateStack extends cdk.NestedStack { constructor(scope: cdk.Construct, id: string, props: CertificateProps) { super(scope, id, props); const stack = cdk.Stack.of(this); const domainName = props.domainName; const project = new codebuild.Project(this, `CertificateProject`, { environment: { buildImage: codebuild.LinuxBuildImage.fromDockerRegistry('debian:buster'), }, buildSpec: codebuild.BuildSpec.fromObject({ version: 0.2, phases: { build: { commands: [ "set -ex", "sed -E -i \"s/(deb.debian.org|security.debian.org)/opentuna.cn/\" /etc/apt/sources.list", "apt-get update", "apt-get install -y python3-pip curl unzip jq", "curl --retry 3 --retry-delay 5 https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip -o awscliv2.zip", "unzip awscliv2.zip", "./aws/install", "pip3 install -i https://opentuna.cn/pypi/web/simple pyopenssl cryptography==3.3.2", "pip3 install -i https://opentuna.cn/pypi/web/simple certbot==1.11.0 certbot-dns-route53==1.11.0", "for i in $(seq 1 5); do [ $i -gt 1 ] && sleep 15; certbot certonly --dns-route53 -d $DOMAIN_NAME --email $EMAIL --agree-tos --non-interactive && s=0 && break || s=$?; done; (exit $s)", "export CERT_NAME=$DOMAIN_NAME-$(date +%s)", "export CERT_ID=$(aws iam upload-server-certificate --server-certificate-name $CERT_NAME --certificate-body file:///etc/letsencrypt/live/$DOMAIN_NAME/cert.pem --private-key file:///etc/letsencrypt/live/$DOMAIN_NAME/privkey.pem --certificate-chain file:///etc/letsencrypt/live/$DOMAIN_NAME/chain.pem --path /cloudfront/opentuna/ | jq '.ServerCertificateMetadata.ServerCertificateId' --raw-output)", "export ORIGINAL_ETAG=$(aws cloudfront get-distribution-config --id $DISTRIBUTIONID --query 'ETag' --output text)", "aws cloudfront get-distribution-config --id $DISTRIBUTIONID --query 'DistributionConfig' --output json | jq \".ViewerCertificate.IAMCertificateId=\\\"$CERT_ID\\\"\" | jq \".ViewerCertificate.Certificate=\\\"$CERT_ID\\\"\" >/tmp/$DISTRIBUTIONID-config.json", "aws cloudfront update-distribution --id $DISTRIBUTIONID --if-match $ORIGINAL_ETAG --distribution-config file:///tmp/$DISTRIBUTIONID-config.json", ] } }, env: { variables: { "DEBIAN_FRONTEND": "noninteractive", "DOMAIN_NAME": domainName, "EMAIL": props.contactEmail, "DISTRIBUTIONID": props.distributionId, }, 'exported-variables': [ 'CERT_NAME', 'CERT_ID', ] } }) }); // Notify SNS Topic project.onBuildFailed(`CertificateProjectFailedSNS`, { target: new targets.SnsTopic(props.notifyTopic, { message: events.RuleTargetInput.fromObject({ type: 'certificate', certificateDomain: domainName, certificateProjectName: events.EventField.fromPath('$.detail.project-name'), certificateBuildStatus: events.EventField.fromPath('$.detail.build-status'), certificateBuildId: events.EventField.fromPath('$.detail.build-id'), account: events.EventField.account, }), }) }); const ruleName = 'opentuna-cert-renew-scheduler-rule'; const certRenewSchedulerFn = new lambda_nodejs.NodejsFunction(this, 'CertRenewScheduler', { entry: path.join(__dirname, './lambda.d/cert-renew-scheduler/index.ts'), handler: 'certRenewScheduler', timeout: cdk.Duration.minutes(1), runtime: lambda.Runtime.NODEJS_12_X, }); certRenewSchedulerFn.addToRolePolicy(new iam.PolicyStatement({ actions: [ 'events:PutRule', 'events:PutTargets', ], effect: iam.Effect.ALLOW, resources: [ cdk.Arn.format({ service: 'events', resource: 'rule', resourceName: ruleName, }, stack), ], })); certRenewSchedulerFn.addToRolePolicy(new iam.PolicyStatement({ actions: ['iam:PassRole'], resources: ['*'], effect: iam.Effect.ALLOW, })); const certRenewSchedulerAlarm = new cloudwatch.Alarm(this, 'CertRenewSchedulerAlarm', { metric: certRenewSchedulerFn.metricErrors({ period: cdk.Duration.minutes(5) }), alarmDescription: `Cert renew scheduler alarm`, threshold: 1, evaluationPeriods: 1, treatMissingData: cloudwatch.TreatMissingData.IGNORE, actionsEnabled: true, }); certRenewSchedulerAlarm.addAlarmAction(new cw_actions.SnsAction(props.notifyTopic)); const iamCertBuildRuleRole = new iam.Role(this, 'IamCertBuildRuleRole', { assumedBy: new iam.ServicePrincipal('events.amazonaws.com'), inlinePolicies: { codebuild: new iam.PolicyDocument({ statements: [new iam.PolicyStatement({ actions: ['codebuild:StartBuild'], resources: [project.projectArn], effect: iam.Effect.ALLOW, })] }), } }); const iamCertBuildRule = project.onBuildSucceeded(`CertificateProjectSuccessSNS`, { target: new targets.LambdaFunction(certRenewSchedulerFn, { event: events.RuleTargetInput.fromObject({ ruleName, certificateProjectARN: project.projectArn, interval: this.node.tryGetContext('certRenewInterval') ?? (90 - 21), ruleRole: iamCertBuildRuleRole.roleArn, }), }), }); const certIssuedTopic = this.node.tryGetContext('certTopicArn'); if (certIssuedTopic) { const eventSenderFn = new lambda_nodejs.NodejsFunction(this, 'IAMCertEventSender', { entry: path.join(__dirname, './lambda.d/iam-cert-event-sender/index.ts'), handler: 'iamCertEventSender', timeout: cdk.Duration.minutes(1), runtime: lambda.Runtime.NODEJS_12_X, environment: { TOPIC_ARN: certIssuedTopic, }, }); eventSenderFn.addToRolePolicy(new iam.PolicyStatement({ actions: ['sns:Publish',], effect: iam.Effect.ALLOW, resources: [certIssuedTopic], })); const eventNotifyAlarm = new cloudwatch.Alarm(this, 'IAMEventNotifyAlarm', { metric: eventSenderFn.metricErrors({ period: cdk.Duration.minutes(5) }), alarmDescription: `IAM cert event notify alarm`, threshold: 1, evaluationPeriods: 1, treatMissingData: cloudwatch.TreatMissingData.IGNORE, actionsEnabled: true, }); eventNotifyAlarm.addAlarmAction(new cw_actions.SnsAction(props.notifyTopic)); iamCertBuildRule.addTarget(new targets.LambdaFunction(eventSenderFn, { event: events.RuleTargetInput.fromObject({ type: 'certificate', certificateDomain: domainName, stage: this.node.tryGetContext('confStage') || 'prod', iamCertId: events.EventField.fromPath('$.detail.additional-information.exported-environment-variables[0].value'), iamCertName: events.EventField.fromPath('$.detail.additional-information.exported-environment-variables[1].value'), certificateProjectName: events.EventField.fromPath('$.detail.project-name'), certificateBuildStatus: events.EventField.fromPath('$.detail.build-status'), certificateBuildId: events.EventField.fromPath('$.detail.build-id'), account: events.EventField.account, }), })); } // permissions required by certbot-dns-route53 plugin project.addToRolePolicy(new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ["route53:ListHostedZones", "route53:GetChange"], resources: ["*"] })) project.addToRolePolicy(new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ["route53:ChangeResourceRecordSets"], resources: [props.hostedZone.hostedZoneArn] })) // permissions for iam server certificate upload project.addToRolePolicy(new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ["iam:UploadServerCertificate"], resources: ["*"] })) // permissions for updating existing cloudfront configuration project.addToRolePolicy(new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ["cloudfront:GetDistributionConfig", "cloudfront:UpdateDistribution"], resources: [cdk.Arn.format({ partition: stack.partition, region: '*', service: 'cloudfront', resource: 'distribution', resourceName: props.distributionId, }, stack)] })); } }
the_stack
import * as State from "./NeovimEditorStore" import * as Actions from "./NeovimEditorActions" import { IConfigurationValues } from "./../../Services/Configuration" import { Errors } from "./../../Services/Diagnostics" import * as pick from "lodash/pick" export function reducer<K extends keyof IConfigurationValues>( s: State.IState, a: Actions.Action<K>, ): State.IState { if (!s) { return s } switch (a.type) { case "SET_HAS_FOCUS": return { ...s, hasFocus: a.payload.hasFocus, } case "SET_COLORS": return { ...s, colors: a.payload.colors, } case "SET_LOADING_COMPLETE": return { ...s, isLoaded: true, } case "SET_NEOVIM_ERROR": return { ...s, neovimError: a.payload.neovimError, } case "SET_VIEWPORT": return { ...s, viewport: viewportReducer(s.viewport, a), } case "SET_CURSOR_SCALE": return { ...s, cursorScale: a.payload.cursorScale, } case "SET_ACTIVE_VIM_TAB_PAGE": return { ...s, activeVimTabPage: a.payload, } case "SET_CURSOR_POSITION": return { ...s, cursorPixelX: a.payload.pixelX, cursorPixelY: a.payload.pixelY, fontPixelWidth: a.payload.fontPixelWidth, fontPixelHeight: a.payload.fontPixelHeight, cursorCharacter: a.payload.cursorCharacter, cursorPixelWidth: a.payload.cursorPixelWidth, } case "SET_IME_ACTIVE": return { ...s, imeActive: a.payload.imeActive, } case "SET_FONT": return { ...s, fontFamily: a.payload.fontFamily, fontSize: a.payload.fontSize, fontWeight: a.payload.fontWeight, } case "SET_MODE": return { ...s, ...{ mode: a.payload.mode } } case "SET_CONFIGURATION_VALUE": const obj: Partial<IConfigurationValues> = {} obj[a.payload.key] = a.payload.value const newConfig = { ...s.configuration, ...obj } return { ...s, configuration: newConfig, } case "SHOW_WILDMENU": return { ...s, wildmenu: { ...s.wildmenu, visible: true, options: a.payload.options, }, } case "WILDMENU_SELECTED": return { ...s, wildmenu: { ...s.wildmenu, selected: a.payload.selected, }, } case "HIDE_WILDMENU": return { ...s, wildmenu: { ...s.wildmenu, visible: false, }, } case "SHOW_COMMAND_LINE": // Array<[any, string]> const [[, content]] = a.payload.content return { ...s, commandLine: { content, visible: true, position: a.payload.position, firstchar: a.payload.firstchar, prompt: a.payload.prompt, indent: a.payload.indent, level: a.payload.level, }, } case "HIDE_COMMAND_LINE": return { ...s, commandLine: { visible: false, content: null, firstchar: "", position: null, prompt: "", indent: null, level: null, }, } case "SET_COMMAND_LINE_POSITION": return { ...s, commandLine: { ...s.commandLine, position: a.payload.position, level: a.payload.level, }, } default: return { ...s, buffers: buffersReducer(s.buffers, a), definition: definitionReducer(s.definition, a), layers: layersReducer(s.layers, a), tabState: tabStateReducer(s.tabState, a), errors: errorsReducer(s.errors, a), toolTips: toolTipsReducer(s.toolTips, a), windowState: windowStateReducer(s.windowState, a), } } } export const layersReducer = (s: State.Layers, a: Actions.SimpleAction) => { switch (a.type) { case "ADD_BUFFER_LAYER": { const currentLayers = s[a.payload.bufferId] || [] if (currentLayers.find(layer => layer.id === a.payload.layer.id)) { return s } return { ...s, [a.payload.bufferId]: [...currentLayers, a.payload.layer], } } case "REMOVE_BUFFER_LAYER": { const currentLayers = s[a.payload.bufferId] || [] return { ...s, [a.payload.bufferId]: currentLayers.filter(l => l !== a.payload.layer), } } default: return s } } export const definitionReducer = (s: State.IDefinition, a: Actions.SimpleAction) => { switch (a.type) { case "SHOW_DEFINITION": const { definitionLocation, token } = a.payload return { definitionLocation, token, } case "HIDE_DEFINITION": return null default: return s } } export const viewportReducer = (s: State.IViewport, a: Actions.ISetViewportAction) => { const { width, height } = a.payload switch (a.type) { case "SET_VIEWPORT": return { ...s, width, height, } default: return s } } export const tabStateReducer = (s: State.ITabState, a: Actions.SimpleAction): State.ITabState => { switch (a.type) { case "SET_TABS": return { ...s, ...a.payload, } default: return s } } export const buffersReducer = ( s: State.IBufferState, a: Actions.SimpleAction, ): State.IBufferState => { let byId = s.byId let allIds = s.allIds const emptyBuffer = (id: number): State.IBuffer => ({ id, file: null, modified: false, hidden: true, listed: false, totalLines: 0, }) switch (a.type) { case "BUFFER_ENTER": byId = a.payload.buffers.reduce((buffersById, buffer) => { buffersById[buffer.id] = { ...buffer, } return byId }, byId) const bufIds = a.payload.buffers.map(b => b.id) allIds = [...new Set(bufIds)] return { activeBufferId: a.payload.buffers[0].id, byId, allIds, } case "BUFFER_SAVE": const currentItem = s.byId[a.payload.id] || emptyBuffer(a.payload.id) byId = { ...s.byId, [a.payload.id]: { ...currentItem, id: a.payload.id, modified: a.payload.modified, lastSaveVersion: a.payload.version, }, } return { ...s, byId, } case "BUFFER_UPDATE": const currentItem3 = s.byId[a.payload.id] || emptyBuffer(a.payload.id) // If the last save version hasn't been set, this means it is the first update, // and should clamp to the incoming version const lastSaveVersion = currentItem3.lastSaveVersion || a.payload.version byId = { ...s.byId, [a.payload.id]: { ...currentItem3, id: a.payload.id, modified: a.payload.modified, totalLines: a.payload.totalLines, lastSaveVersion, }, } return { ...s, byId, } case "SET_CURRENT_BUFFERS": allIds = s.allIds.filter(id => a.payload.bufferIds.indexOf(id) >= 0) let activeBufferId = s.activeBufferId if (a.payload.bufferIds.indexOf(activeBufferId) === -1) { activeBufferId = null } const newById: any = pick(s.byId, a.payload.bufferIds) return { activeBufferId, byId: newById, allIds, } default: return s } } export const errorsReducer = (s: Errors, a: Actions.SimpleAction) => { switch (a.type) { case "SET_ERRORS": return { ...a.payload.errors, } default: return s } } export const toolTipsReducer = (s: State.ToolTips, a: Actions.SimpleAction): State.ToolTips => { switch (a.type) { case "SHOW_TOOL_TIP": const existingItem = s[a.payload.id] || {} const newItem = { ...existingItem, ...a.payload, } return { ...s, [a.payload.id]: newItem, } case "HIDE_TOOL_TIP": return { ...s, [a.payload.id]: null, } default: return s } } export const windowStateReducer = ( s: State.IWindowState, a: Actions.SimpleAction, ): State.IWindowState => { let currentWindow switch (a.type) { case "SET_WINDOW_CURSOR": currentWindow = s.windows[a.payload.windowId] || null return { activeWindow: a.payload.windowId, windows: { ...s.windows, [a.payload.windowId]: { ...currentWindow, column: a.payload.column, line: a.payload.line, }, }, } case "SET_INACTIVE_WINDOW_STATE": currentWindow = s.windows[a.payload.windowId] || null return { ...s, windows: { ...s.windows, [a.payload.windowId]: { ...currentWindow, windowId: a.payload.windowId, column: -1, line: -1, topBufferLine: -1, bottomBufferLine: -1, dimensions: a.payload.dimensions, }, }, } case "SET_WINDOW_STATE": currentWindow = s.windows[a.payload.windowId] || null return { activeWindow: a.payload.windowId, windows: { ...s.windows, [a.payload.windowId]: { ...currentWindow, file: a.payload.file, bufferId: a.payload.bufferId, windowId: a.payload.windowId, column: a.payload.column, line: a.payload.line, bufferToScreen: a.payload.bufferToScreen, screenToPixel: a.payload.screenToPixel, bufferToPixel: a.payload.bufferToPixel, dimensions: a.payload.dimensions, topBufferLine: a.payload.topBufferLine, bottomBufferLine: a.payload.bottomBufferLine, visibleLines: a.payload.visibleLines, }, }, } default: return s } }
the_stack
import { compileSol, compileSourceString, LatestCompilerVersion } from "solc-typed-ast"; import BN from "bn.js"; import crypto from "crypto"; import Account from "ethereumjs-account"; import { Transaction } from "ethereumjs-tx"; import * as util from "ethereumjs-util"; import VM from "ethereumjs-vm"; import { RunTxResult } from "ethereumjs-vm/dist/runTx"; import expect from "expect"; const abi = require("ethereumjs-abi"); const { promisify } = require("util"); export type AliasMap = Map<string, any>; export type ContractBytecodeMap = Map<string, Buffer>; export type LogEntry = [Buffer[], any[]]; export interface Environment { vm: VM; aliases: AliasMap; contracts: ContractBytecodeMap; } export interface AliasReference { alias: string; } export interface CallArgs { types: string[]; values: any[]; } export interface CallOptions { method: string; args?: CallArgs; returns?: string[]; logs?: string[][]; } export interface Step { act: string; [key: string]: any; } export interface Config { file: string; contents?: string; steps: Step[]; } type StepProcessor = (env: Environment, step: Step) => void; class User { readonly privateKey: Buffer; readonly address: Buffer; constructor(privateKey: Buffer) { this.privateKey = privateKey; this.address = util.privateToAddress(privateKey); } async register(vm: VM, data?: any) { const stateManager = vm.stateManager; const put = promisify(stateManager.putAccount.bind(stateManager)); await put(this.address, new Account(data)); } async getAccount(vm: VM): Promise<Account> { const stateManager = vm.stateManager; const get = promisify(stateManager.getAccount.bind(stateManager)); return get(this.address); } } /** * @see https://github.com/b-mueller/sabre/blob/master/lib/compiler.js#L222-L229 */ function compileSource( fileName: string, contents?: string, version: string = LatestCompilerVersion ): ContractBytecodeMap { let data: any; if (contents) { data = compileSourceString(fileName, contents, version, []).data; } else { data = compileSol(fileName, "auto", []).data; } const result = new Map<string, Buffer>(); const contracts: { [name: string]: any } = data.contracts[fileName]; for (const [name, meta] of Object.entries(contracts)) { const bytecode = meta && meta.evm && meta.evm.bytecode && meta.evm.bytecode.object; if (bytecode !== undefined) { result.set(name, Buffer.from(bytecode, "hex")); } } return result; } function encodeCallArgs(args: CallArgs): Buffer { return abi.rawEncode(args.types, args.values); } function createCallPayload(options: CallOptions): Buffer { if (options.args === undefined) { return abi.methodID(options.method, []); } const args = encodeCallArgs(options.args); const selector: Buffer = abi.methodID(options.method, options.args.types); return Buffer.concat([selector, args]); } function extractTxLogs(specifications: string[][], result: RunTxResult): LogEntry[] { const logs: LogEntry[] = []; if (result.execResult.logs) { for (let i = 0; i < specifications.length; i++) { const types = specifications[i]; const log = result.execResult.logs[i]; const topics: Buffer[] = log[1]; const values: any[] = abi.rawDecode(types, log[2]); logs.push([topics, values]); } } return logs; } async function deployContract( vm: VM, sender: User, bytecode: Buffer, args?: CallArgs, logs?: string[][] ): Promise<[Buffer | undefined, LogEntry[]]> { const payload = args ? Buffer.concat([bytecode, encodeCallArgs(args)]) : bytecode; const tx = new Transaction({ value: 0, gasLimit: 200000000, gasPrice: 1, data: payload, nonce: (await sender.getAccount(vm)).nonce }); tx.sign(sender.privateKey); const result = await vm.runTx({ tx }); const exception = result.execResult.exceptionError; if (exception) { throw new Error(exception.error); } const emittedLogs = logs ? extractTxLogs(logs, result) : []; return [result.createdAddress, emittedLogs]; } async function txCall( vm: VM, sender: User, contractAddress: Buffer, options: CallOptions ): Promise<[any[], LogEntry[]]> { const tx = new Transaction({ to: contractAddress, value: 0, gasLimit: 2000000, gasPrice: 1, data: createCallPayload(options), nonce: (await sender.getAccount(vm)).nonce }); tx.sign(sender.privateKey); const result = await vm.runTx({ tx }); const exception = result.execResult.exceptionError; if (exception) { throw new Error(exception.error); } const values = options.returns === undefined ? [] : abi.rawDecode(options.returns, result.execResult.returnValue); const logs = options.logs ? extractTxLogs(options.logs, result) : []; return [values, logs]; } async function staticCall( vm: VM, caller: User, contractAddress: Buffer, options: CallOptions ): Promise<any[]> { const result = await vm.runCall({ to: contractAddress, caller: caller.address, origin: caller.address, data: createCallPayload(options) }); const exception = result.execResult.exceptionError; if (exception) { throw new Error(exception.error); } const values = options.returns === undefined ? [] : abi.rawDecode(options.returns, result.execResult.returnValue); return values; } function getContractByteCode(contracts: ContractBytecodeMap, name: string): Buffer { const bytecode = contracts.get(name); if (bytecode === undefined) { throw new Error(`Bytecode for contract "${name}" not found in compiler output`); } return bytecode; } function isAliasReference(value: any): value is AliasReference { if (value === undefined || value === null) { return false; } return typeof value.alias === "string"; } function resolveAlias(aliases: AliasMap, key: string): any { const value = aliases.get(key); if (value === undefined) { throw new Error(`Aliased value for key "${key}" is not defined`); } return value; } function resolveUserAlias(aliases: AliasMap, key: string): User { const value = resolveAlias(aliases, key); if (value instanceof User) { return value; } throw new Error(`Aliased value for key "${key}" is not a user`); } function resolveAddressAlias(aliases: AliasMap, key: string): Buffer { const value = resolveAlias(aliases, key); if (value instanceof Buffer && value.length === 20) { return value; } throw new Error(`Aliased value for key "${key}" is not an address`); } /** * Replaces any alias references, that are supplied in `values`, * by extracting corresponding values from `aliases` map. * * Note that results are required to be compatible with * ABI raw encoding requirements: * any `Buffer`s should be converted to hex string values. * * The function is supposed to be applied to a call arguments, * prior their use in `txCall()`, `staticCall()` or `deployContract()`. */ function patchCallValues(values: any[], aliases: AliasMap): any[] { const result: any[] = []; for (const value of values) { if (isAliasReference(value)) { let resolved = resolveAlias(aliases, value.alias); if (resolved instanceof User) { resolved = resolved.address; } if (resolved instanceof Buffer) { resolved = "0x" + resolved.toString("hex"); } result.push(resolved); } else { result.push(value); } } return result; } function processReturns(aliases: AliasMap, tasks: any[], values: any[]): void { for (let i = 0; i < tasks.length; i++) { const task = tasks[i]; if (task === null) { continue; } const actual = values[i]; if (task.alias) { aliases.set(task.alias, actual); } if (task.expect) { if (isAliasReference(task.expect)) { const expected = resolveAlias(aliases, task.expect.alias); expect(actual).toEqual(expected); } else { const expected = task.expect; expect(actual instanceof BN ? actual.toString() : actual).toEqual(expected); } } } } function processLogs(aliases: AliasMap, tasks: any[], logs: LogEntry[]): void { for (let i = 0; i < tasks.length; i++) { const expectations = tasks[i]; if (expectations === null) { continue; } const [, values] = logs[i]; for (let v = 0; v < expectations.length; v++) { if (isAliasReference(expectations[v])) { const expected = resolveAlias(aliases, expectations[v].alias); const actual = values[v]; expect(actual).toEqual(expected); } else { const expected = expectations[v]; let actual = values[v] instanceof BN ? values[v].toString() : values[v]; if (actual instanceof Buffer) { actual = actual.toJSON().data; } expect(actual).toEqual(expected); } } } } const processors = new Map<string, StepProcessor>([ [ "createUser", (env: Environment, step: Step) => { it(`User ${step.alias} registers`, async () => { const privateKey = crypto.randomBytes(32); const user = new User(privateKey); await user.register(env.vm, step.options); env.aliases.set(step.alias, user); }); } ], [ "deployContract", (env: Environment, step: Step) => { it(`User ${step.user} deploys ${step.contract} as ${step.alias}`, async () => { const sender = resolveUserAlias(env.aliases, step.user); const bytecode = getContractByteCode(env.contracts, step.contract); if (step.args !== undefined) { step.args.values = patchCallValues(step.args.values, env.aliases); } const call = deployContract(env.vm, sender, bytecode, step.args, step.logs); if (step.failure) { await expect(call).rejects.toThrow( step.failure === "*" ? undefined : step.failure ); } else { const [address, logs] = await call; if (address === undefined) { throw new Error( `Deployment address for contract "${step.name}" is undefined` ); } env.aliases.set(step.alias, address); if (step.onLogs) { processLogs(env.aliases, step.onLogs, logs); } } }); } ], [ "staticCall", (env: Environment, step: Step) => { it(`User ${step.user} calls ${step.contract}.${step.method}() statically`, async () => { const caller = resolveUserAlias(env.aliases, step.user); const address = resolveAddressAlias(env.aliases, step.contract); const options: CallOptions = { method: step.method, args: step.args, returns: step.returns }; if (options.args !== undefined) { options.args.values = patchCallValues(options.args.values, env.aliases); } const call = staticCall(env.vm, caller, address, options); if (step.failure) { await expect(call).rejects.toThrow( step.failure === "*" ? undefined : step.failure ); } else { const values = await call; if (step.onReturns) { processReturns(env.aliases, step.onReturns, values); } } }); } ], [ "txCall", (env: Environment, step: Step) => { it(`User ${step.user} calls ${step.contract}.${step.method}()`, async () => { const sender = resolveUserAlias(env.aliases, step.user); const address = resolveAddressAlias(env.aliases, step.contract); const options: CallOptions = { method: step.method, args: step.args, returns: step.returns, logs: step.logs }; if (options.args !== undefined) { options.args.values = patchCallValues(options.args.values, env.aliases); } const call = txCall(env.vm, sender, address, options); if (step.failure) { await expect(call).rejects.toThrow( step.failure === "*" ? undefined : step.failure ); } else { const [values, logs] = await call; if (step.onReturns) { processReturns(env.aliases, step.onReturns, values); } if (step.onLogs) { processLogs(env.aliases, step.onLogs, logs); } } }); } ] ]); /** * @see https://github.com/ethereumjs/ethereumjs-vm/tree/master/packages/vm/examples/run-solidity-contract */ export function executeTestSuite(fileName: string, config: Config): void { const sample = config.file; describe(`Test suite ${fileName} with sample ${sample}`, () => { const env = {} as Environment; before(() => { env.vm = new VM(); env.aliases = new Map<string, any>(); env.contracts = compileSource(sample, config.contents); }); for (const step of config.steps) { const processor = processors.get(step.act); if (processor === undefined) { throw new Error(`Unsupported step "${step.act}"`); } processor(env, step); } }); } /** * Internal version of executeTestSuite that may be called from another mocha test. * @todo remove code duplication with executeTestSuite */ export function executeTestSuiteInternal(fileName: string, config: Config, version: string): void { const sample = config.file; const env = {} as Environment; env.vm = new VM(); env.aliases = new Map<string, any>(); env.contracts = compileSource(sample, config.contents, version); for (const step of config.steps) { const processor = processors.get(step.act); if (processor === undefined) { throw new Error(`Unsupported step "${step.act}"`); } processor(env, step); } }
the_stack
import { Callback, Handler } from 'aws-lambda'; import * as Sentry from '../src'; const { wrapHandler } = Sentry.AWSLambda; /** * Why @ts-ignore some Sentry.X calls * * A hack-ish way to contain everything related to mocks in the same __mocks__ file. * Thanks to this, we don't have to do more magic than necessary. Just add and export desired method and assert on it. */ // Default `timeoutWarningLimit` is 500ms so leaving some space for it to trigger when necessary const DEFAULT_EXECUTION_TIME = 100; let fakeEvent: { [key: string]: unknown }; const fakeContext = { callbackWaitsForEmptyEventLoop: false, functionName: 'functionName', functionVersion: 'functionVersion', invokedFunctionArn: 'invokedFunctionArn', memoryLimitInMB: 'memoryLimitInMB', awsRequestId: 'awsRequestId', logGroupName: 'logGroupName', logStreamName: 'logStreamName', getRemainingTimeInMillis: () => DEFAULT_EXECUTION_TIME, done: () => {}, fail: () => {}, succeed: () => {}, ytho: 'o_O', }; const fakeCallback: Callback = (err, result) => { if (err === null || err === undefined) { return result; } return err; }; function expectScopeSettings() { // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeScope.setSpan).toBeCalledWith(Sentry.fakeTransaction); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeScope.setTag).toBeCalledWith('server_name', expect.anything()); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeScope.setTag).toBeCalledWith('url', 'awslambda:///functionName'); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeScope.setContext).toBeCalledWith('runtime', { name: 'node', version: expect.anything() }); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeScope.setContext).toBeCalledWith( 'aws.lambda', expect.objectContaining({ aws_request_id: 'awsRequestId', function_name: 'functionName', function_version: 'functionVersion', invoked_function_arn: 'invokedFunctionArn', remaining_time_in_millis: 100, }), ); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeScope.setContext).toBeCalledWith( 'aws.cloudwatch.logs', expect.objectContaining({ log_group: 'logGroupName', log_stream: 'logStreamName', }), ); } describe('AWSLambda', () => { beforeEach(() => { fakeEvent = { fortySix: 'o_O', }; }); afterEach(() => { // @ts-ignore see "Why @ts-ignore" note Sentry.resetMocks(); }); describe('wrapHandler() options', () => { test('flushTimeout', async () => { expect.assertions(1); const handler = () => {}; const wrappedHandler = wrapHandler(handler, { flushTimeout: 1337 }); await wrappedHandler(fakeEvent, fakeContext, fakeCallback); expect(Sentry.flush).toBeCalledWith(1337); }); test('captureTimeoutWarning enabled (default)', async () => { expect.assertions(2); const handler: Handler = (_event, _context, callback) => { setTimeout(() => { callback(null, 42); }, DEFAULT_EXECUTION_TIME); }; const wrappedHandler = wrapHandler(handler); await wrappedHandler(fakeEvent, fakeContext, fakeCallback); expect(Sentry.captureMessage).toBeCalled(); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeScope.setTag).toBeCalledWith('timeout', '1s'); }); test('captureTimeoutWarning disabled', async () => { expect.assertions(2); const handler: Handler = (_event, _context, callback) => { setTimeout(() => { callback(null, 42); }, DEFAULT_EXECUTION_TIME); }; const wrappedHandler = wrapHandler(handler, { captureTimeoutWarning: false, }); await wrappedHandler(fakeEvent, fakeContext, fakeCallback); expect(Sentry.withScope).not.toBeCalled(); expect(Sentry.captureMessage).not.toBeCalled(); }); test('captureTimeoutWarning with configured timeoutWarningLimit', async () => { /** * This extra long `getRemainingTimeInMillis` is enough to prove that `timeoutWarningLimit` is working * as warning delay is internally implemented as `context.getRemainingTimeInMillis() - options.timeoutWarningLimit`. * If it would not work as expected, we'd exceed `setTimeout` used and never capture the warning. */ expect.assertions(2); const handler: Handler = (_event, _context, callback) => { setTimeout(() => { callback(null, 42); }, DEFAULT_EXECUTION_TIME); }; const wrappedHandler = wrapHandler(handler, { timeoutWarningLimit: 99950, // 99.95s (which triggers warning after 50ms of our configured 100s below) }); await wrappedHandler( fakeEvent, { ...fakeContext, getRemainingTimeInMillis: () => 100000, // 100s - using such a high value to test human-readable format in one of the assertions }, fakeCallback, ); expect(Sentry.captureMessage).toBeCalled(); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeScope.setTag).toBeCalledWith('timeout', '1m40s'); }); test('captureAllSettledReasons disabled (default)', async () => { const handler = () => Promise.resolve([{ status: 'rejected', reason: new Error() }]); const wrappedHandler = wrapHandler(handler, { flushTimeout: 1337 }); await wrappedHandler(fakeEvent, fakeContext, fakeCallback); expect(Sentry.captureException).toBeCalledTimes(0); }); test('captureAllSettledReasons enable', async () => { const error = new Error(); const error2 = new Error(); const handler = () => Promise.resolve([ { status: 'rejected', reason: error }, { status: 'fulfilled', value: undefined }, { status: 'rejected', reason: error2 }, ]); const wrappedHandler = wrapHandler(handler, { flushTimeout: 1337, captureAllSettledReasons: true }); await wrappedHandler(fakeEvent, fakeContext, fakeCallback); expect(Sentry.captureException).toHaveBeenNthCalledWith(1, error); expect(Sentry.captureException).toHaveBeenNthCalledWith(2, error2); expect(Sentry.captureException).toBeCalledTimes(2); }); }); describe('wrapHandler() on sync handler', () => { test('successful execution', async () => { expect.assertions(10); const handler: Handler = (_event, _context, callback) => { callback(null, 42); }; const wrappedHandler = wrapHandler(handler); const rv = await wrappedHandler(fakeEvent, fakeContext, fakeCallback); expect(rv).toStrictEqual(42); expect(Sentry.startTransaction).toBeCalledWith({ name: 'functionName', op: 'awslambda.handler' }); expectScopeSettings(); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeTransaction.finish).toBeCalled(); expect(Sentry.flush).toBeCalledWith(2000); }); test('unsuccessful execution', async () => { expect.assertions(10); const error = new Error('sorry'); const handler: Handler = (_event, _context, callback) => { callback(error); }; const wrappedHandler = wrapHandler(handler); try { await wrappedHandler(fakeEvent, fakeContext, fakeCallback); } catch (e) { expect(Sentry.startTransaction).toBeCalledWith({ name: 'functionName', op: 'awslambda.handler' }); expectScopeSettings(); expect(Sentry.captureException).toBeCalledWith(error); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeTransaction.finish).toBeCalled(); expect(Sentry.flush).toBeCalledWith(2000); } }); test('event and context are correctly passed along', async () => { expect.assertions(2); const handler: Handler = (event, context, callback) => { expect(event).toHaveProperty('fortySix'); expect(context).toHaveProperty('ytho'); callback(undefined, { its: 'fine' }); }; const wrappedHandler = wrapHandler(handler); await wrappedHandler(fakeEvent, fakeContext, fakeCallback); }); test('incoming trace headers are correctly parsed and used', async () => { expect.assertions(1); fakeEvent.headers = { 'sentry-trace': '12312012123120121231201212312012-1121201211212012-0', baggage: 'sentry-release=2.12.1,maisey=silly,charlie=goofy', }; const handler: Handler = (_event, _context, callback) => { expect(Sentry.startTransaction).toBeCalledWith( expect.objectContaining({ parentSpanId: '1121201211212012', parentSampled: false, op: 'awslambda.handler', name: 'functionName', traceId: '12312012123120121231201212312012', metadata: { baggage: [ { release: '2.12.1', }, 'maisey=silly,charlie=goofy', ], }, }), ); callback(undefined, { its: 'fine' }); }; const wrappedHandler = wrapHandler(handler); await wrappedHandler(fakeEvent, fakeContext, fakeCallback); }); test('capture error', async () => { expect.assertions(10); const error = new Error('wat'); const handler: Handler = (_event, _context, _callback) => { throw error; }; const wrappedHandler = wrapHandler(handler); try { fakeEvent.headers = { 'sentry-trace': '12312012123120121231201212312012-1121201211212012-0' }; await wrappedHandler(fakeEvent, fakeContext, fakeCallback); } catch (e) { expect(Sentry.startTransaction).toBeCalledWith({ name: 'functionName', op: 'awslambda.handler', traceId: '12312012123120121231201212312012', parentSpanId: '1121201211212012', parentSampled: false, }); expectScopeSettings(); expect(Sentry.captureException).toBeCalledWith(e); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeTransaction.finish).toBeCalled(); expect(Sentry.flush).toBeCalled(); } }); }); describe('wrapHandler() on async handler', () => { test('successful execution', async () => { expect.assertions(10); const handler: Handler = async (_event, _context) => { return 42; }; const wrappedHandler = wrapHandler(handler); const rv = await wrappedHandler(fakeEvent, fakeContext, fakeCallback); expect(rv).toStrictEqual(42); expect(Sentry.startTransaction).toBeCalledWith({ name: 'functionName', op: 'awslambda.handler' }); expectScopeSettings(); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeTransaction.finish).toBeCalled(); expect(Sentry.flush).toBeCalled(); }); test('event and context are correctly passed to the original handler', async () => { expect.assertions(2); const handler: Handler = async (event, context) => { expect(event).toHaveProperty('fortySix'); expect(context).toHaveProperty('ytho'); }; const wrappedHandler = wrapHandler(handler); await wrappedHandler(fakeEvent, fakeContext, fakeCallback); }); test('capture error', async () => { expect.assertions(10); const error = new Error('wat'); const handler: Handler = async (_event, _context) => { throw error; }; const wrappedHandler = wrapHandler(handler); try { await wrappedHandler(fakeEvent, fakeContext, fakeCallback); } catch (e) { expect(Sentry.startTransaction).toBeCalledWith({ name: 'functionName', op: 'awslambda.handler' }); expectScopeSettings(); expect(Sentry.captureException).toBeCalledWith(error); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeTransaction.finish).toBeCalled(); expect(Sentry.flush).toBeCalled(); } }); test('should not throw when flush rejects', async () => { const handler: Handler = async () => { // Friendly handler with no errors :) return 'some string'; }; const wrappedHandler = wrapHandler(handler); jest.spyOn(Sentry, 'flush').mockImplementationOnce(async () => { throw new Error(); }); await expect(wrappedHandler(fakeEvent, fakeContext, fakeCallback)).resolves.toBe('some string'); }); }); describe('wrapHandler() on async handler with a callback method (aka incorrect usage)', () => { test('successful execution', async () => { expect.assertions(10); const handler: Handler = async (_event, _context, _callback) => { return 42; }; const wrappedHandler = wrapHandler(handler); const rv = await wrappedHandler(fakeEvent, fakeContext, fakeCallback); expect(rv).toStrictEqual(42); expect(Sentry.startTransaction).toBeCalledWith({ name: 'functionName', op: 'awslambda.handler' }); expectScopeSettings(); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeTransaction.finish).toBeCalled(); expect(Sentry.flush).toBeCalled(); }); test('event and context are correctly passed to the original handler', async () => { expect.assertions(2); const handler: Handler = async (event, context, _callback) => { expect(event).toHaveProperty('fortySix'); expect(context).toHaveProperty('ytho'); }; const wrappedHandler = wrapHandler(handler); await wrappedHandler(fakeEvent, fakeContext, fakeCallback); }); test('capture error', async () => { expect.assertions(10); const error = new Error('wat'); const handler: Handler = async (_event, _context, _callback) => { throw error; }; const wrappedHandler = wrapHandler(handler); try { await wrappedHandler(fakeEvent, fakeContext, fakeCallback); } catch (e) { expect(Sentry.startTransaction).toBeCalledWith({ name: 'functionName', op: 'awslambda.handler' }); expectScopeSettings(); expect(Sentry.captureException).toBeCalledWith(error); // @ts-ignore see "Why @ts-ignore" note expect(Sentry.fakeTransaction.finish).toBeCalled(); expect(Sentry.flush).toBeCalled(); } }); }); describe('init()', () => { test('calls Sentry.init with correct sdk info metadata', () => { Sentry.AWSLambda.init({}); expect(Sentry.init).toBeCalledWith( expect.objectContaining({ _metadata: { sdk: { name: 'sentry.javascript.serverless', integrations: ['AWSLambda'], packages: [ { name: 'npm:@sentry/serverless', version: '6.6.6', }, ], version: '6.6.6', }, }, }), ); }); test('enhance event with correct mechanism value', () => { const eventWithSomeData = { exception: { values: [{}], }, }; // @ts-ignore see "Why @ts-ignore" note Sentry.addGlobalEventProcessor.mockImplementationOnce(cb => cb(eventWithSomeData)); Sentry.AWSLambda.init({}); expect(eventWithSomeData).toEqual({ exception: { values: [ { mechanism: { handled: false, type: 'generic', }, }, ], }, }); }); }); });
the_stack
module es { export class EntityList { public scene: Scene; /** * 场景中添加的实体列表 */ public _entities: Entity[] = []; /** * 本帧添加的实体列表。用于对实体进行分组,以便我们可以同时处理它们 */ public _entitiesToAdded: {[index: number]: Entity} = {}; /** * 本帧被标记为删除的实体列表。用于对实体进行分组,以便我们可以同时处理它们 */ public _entitiesToRemove: {[index: number]: Entity} = {}; public _entitiesToAddedList: Entity[] = []; public _entitiesToRemoveList: Entity[] = []; /** * 标志,用于确定我们是否需要在这一帧中对实体进行排序 */ public _isEntityListUnsorted: boolean; /** * 通过标签跟踪实体,便于检索 */ public _entityDict: Map<number, Set<Entity>> = new Map<number, Set<Entity>>(); public _unsortedTags: Set<number> = new Set<number>(); constructor(scene: Scene) { this.scene = scene; } public get count() { return this._entities.length; } public get buffer() { return this._entities; } public markEntityListUnsorted() { this._isEntityListUnsorted = true; } public markTagUnsorted(tag: number) { this._unsortedTags.add(tag); } /** * 将一个实体添加到列表中。所有的生命周期方法将在下一帧中被调用 * @param entity */ public add(entity: Entity) { this._entitiesToAdded[entity.id] = entity; this._entitiesToAddedList.push(entity); } /** * 从列表中删除一个实体。所有的生命周期方法将在下一帧中被调用 * @param entity */ public remove(entity: Entity) { // 防止在同一帧中添加或删除实体 if (this._entitiesToAdded[entity.id]) { let index = this._entitiesToAddedList.findIndex(e => e.id == entity.id); if (index != -1) this._entitiesToAddedList.splice(index, 1); delete this._entitiesToAdded[entity.id]; return; } this._entitiesToRemoveList.push(entity); if (!this._entitiesToRemove[entity.id]) this._entitiesToRemove[entity.id] = entity; } /** * 从实体列表中删除所有实体 */ public removeAllEntities() { this._unsortedTags.clear(); this._entitiesToAdded = {}; this._entitiesToAddedList.length = 0; this._isEntityListUnsorted = false; // 为什么我们要在这里更新列表?主要是为了处理在场景切换前被分离的实体。 // 它们仍然会在_entitiesToRemove列表中,这将由updateLists处理。 this.updateLists(); for (let i = 0; i < this._entities.length; i++) { this._entities[i]._isDestroyed = true; this._entities[i].onRemovedFromScene(); this._entities[i].scene = null; } this._entities.length = 0; this._entityDict.clear(); } /** * 检查实体目前是否由这个EntityList管理 * @param entity */ public contains(entity: Entity): boolean { return !!this._entitiesToAdded[entity.id]; } public getTagList(tag: number) { let list = this._entityDict.get(tag); if (!list) { list = new Set(); this._entityDict.set(tag, list); } return list; } public addToTagList(entity: Entity) { this.getTagList(entity.tag).add(entity); this._unsortedTags.add(entity.tag); } public removeFromTagList(entity: Entity) { let list = this._entityDict.get(entity.tag); if (list) list.delete(entity); } public update() { for (let i = 0, s = this._entities.length; i < s; ++ i) { let entity = this._entities[i]; if (entity.enabled && (entity.updateInterval == 1 || Time.frameCount % entity.updateInterval == 0)) entity.update(); } } public updateLists() { if (this._entitiesToRemoveList.length > 0) { for (let i = 0, s = this._entitiesToRemoveList.length; i < s; ++ i) { let entity = this._entitiesToRemoveList[i]; this.removeFromTagList(entity); // 处理常规实体列表 let index = this._entities.findIndex(e => e.id == entity.id); if (index != -1) this._entities.splice(index, 1); entity.onRemovedFromScene(); entity.scene = null; this.scene.entityProcessors.onEntityRemoved(entity); } this._entitiesToRemove = {}; this._entitiesToRemoveList.length = 0; } if (this._entitiesToAddedList.length > 0) { for (let i = 0, s = this._entitiesToAddedList.length; i < s; ++ i) { let entity = this._entitiesToAddedList[i]; this._entities.push(entity); entity.scene = this.scene; this.addToTagList(entity); this.scene.entityProcessors.onEntityAdded(entity); } for (let i = 0, s = this._entitiesToAddedList.length; i < s; ++ i) { let entity = this._entitiesToAddedList[i]; entity.onAddedToScene(); } this._entitiesToAdded = {}; this._entitiesToAddedList.length = 0; } } /** * 返回第一个找到的名字为name的实体。如果没有找到则返回null * @param name */ public findEntity(name: string) { if (this._entities.length > 0) { for (let i = 0, s = this._entities.length; i < s; ++ i) { let entity = this._entities[i]; if (entity.name == name) return entity; } } if (this._entitiesToAddedList.length > 0) { for (let i = 0, s = this._entitiesToAddedList.length; i < s; ++ i) { let entity = this._entitiesToAddedList[i]; if (entity.name == name) return entity; } } return null; } /** * * @param id * @returns */ public findEntityById(id: number) { if (this._entities.length > 0) { for (let i = 0, s = this._entities.length; i < s; ++ i) { let entity = this._entities[i]; if (entity.id == id) return entity; } } return this._entitiesToAdded[id]; } /** * 返回带有标签的所有实体的列表。如果没有实体有标签,则返回一个空列表。 * 返回的List可以通过ListPool.free放回池中 * @param tag */ public entitiesWithTag(tag: number) { let list = this.getTagList(tag); let returnList = ListPool.obtain<Entity>(Entity); if (list.size > 0) { for (let entity of list) { returnList.push(entity); } } return returnList; } /** * 返回第一个找到该tag的实体 * @param tag * @returns */ public entityWithTag(tag: number) { let list = this.getTagList(tag); if (list.size > 0) { for (let entity of list) { return entity; } } return null; } /** * 返回在场景中找到的第一个T类型的组件。 * @param type */ public findComponentOfType<T extends Component>(type): T { if (this._entities.length > 0 ){ for (let i = 0, s = this._entities.length; i < s; i++) { let entity = this._entities[i]; if (entity.enabled) { let comp = entity.getComponent<T>(type); if (comp) return comp; } } } if (this._entitiesToAddedList.length > 0) { for (let i = 0; i < this._entitiesToAddedList.length; i++) { let entity = this._entitiesToAddedList[i]; if (entity.enabled) { let comp = entity.getComponent<T>(type); if (comp) return comp; } } } return null; } /** * 返回在场景中找到的所有T类型的组件。 * 返回的List可以通过ListPool.free放回池中。 * @param type */ public findComponentsOfType<T extends Component>(type): T[] { let comps = ListPool.obtain<T>(type); if (this._entities.length > 0) { for (let i = 0, s = this._entities.length; i < s; i++) { let entity = this._entities[i]; if (entity.enabled) entity.getComponents(type, comps); } } if (this._entitiesToAddedList.length > 0) { for (let i = 0, s = this._entitiesToAddedList.length; i < s; i ++) { let entity = this._entitiesToAddedList[i]; if (entity.enabled) entity.getComponents(type, comps); } } return comps; } /** * 返回场景中包含特定组件的实体列表 * @param types * @returns */ public findEntitiesOfComponent(...types: any[]): Entity[] { let entities = []; if (this._entities.length > 0) { for (let i = 0, s = this._entities.length; i < s; i++) { if (this._entities[i].enabled) { let meet = true; if (types.length > 0) for (let t = 0, ts = types.length; t < ts; t ++) { let type = types[t]; let hasComp = this._entities[i].hasComponent(type); if (!hasComp) { meet = false; break; } } if (meet) { entities.push(this._entities[i]); } } } } if (this._entitiesToAddedList.length > 0) { for (let i = 0, s = this._entitiesToAddedList.length; i < s; i ++) { let entity = this._entitiesToAddedList[i]; if (entity.enabled) { let meet = true; if (types.length > 0) for (let t = 0, ts = types.length; t < ts; t ++) { let type = types[t]; let hasComp = entity.hasComponent(type); if (!hasComp) { meet = false; break; } } if (meet) { entities.push(entity); } } } } return entities; } } }
the_stack
import { BLOCK_MAXSIZE } from "rt/common"; // Helper function to quickly create a Buffer from an array. //@ts-ignore function create<T>(values: valueof<T>[]): T { let result = instantiate<T>(values.length); //@ts-ignore for (let i = 0; i < values.length; i++) result[i] = values[i]; return result; } describe("buffer", () => { test("#constructor", () => { expect(new Buffer(0)).toBeTruthy(); expect(new Buffer(10)).toHaveLength(10); let myBuffer = new Buffer(10); expect(myBuffer.buffer).toBeTruthy(); expect(myBuffer.buffer).toHaveLength(10); expect(() => { new Buffer(-1); }).toThrow(); // TODO: figure out how to test block maxsize // expect(() => { new Buffer(1 + BLOCK_MAXSIZE); }).toThrow(); }); test("#alloc", () => { expect(Buffer.alloc(10)).toBeTruthy(); expect(Buffer.alloc(10)).toHaveLength(10); let buff = Buffer.alloc(100); for (let i = 0; i < buff.length; i++) expect<u8>(buff[i]).toBe(0); expect(buff.buffer).not.toBeNull(); expect(buff.byteLength).toBe(100); expect(() => { Buffer.alloc(-1); }).toThrow(); // TODO: figure out how to test block maxsize // expect(() => { Buffer.alloc(1 + BLOCK_MAXSIZE); }).toThrow(); }); test("#allocUnsafe", () => { expect(Buffer.allocUnsafe(10)).toBeTruthy(); expect(Buffer.allocUnsafe(10)).toHaveLength(10); let buff = Buffer.allocUnsafe(100); expect(buff.buffer).not.toBeNull(); expect(buff.byteLength).toBe(100); expect(() => { Buffer.allocUnsafe(-1); }).toThrow(); // TODO: figure out how to test block maxsize // expect(() => { Buffer.allocUnsafe(BLOCK_MAXSIZE + 1); }).toThrow(); }); test("#isBuffer", () => { let a = ""; let b = new Uint8Array(0); let c = 0; let d = 1.1; let e = new Buffer(0); let f: Buffer | null = null; expect(Buffer.isBuffer(a)).toBeFalsy(); expect(Buffer.isBuffer(b)).toBeFalsy(); expect(Buffer.isBuffer(c)).toBeFalsy(); expect(Buffer.isBuffer(d)).toBeFalsy(); expect(Buffer.isBuffer(e)).toBeTruthy(); expect(Buffer.isBuffer(f)).toBeFalsy(); }); test("#readInt8", () => { let buff = create<Buffer>([0x5,0x0,0x0,0x0,0xFF]); expect(buff.readInt8()).toBe(5); // Testing offset, and casting between u8 and i8. expect(buff.readInt8(4)).toBe(-1); expect(() => { let newBuff = new Buffer(1); newBuff.readInt8(5); }).toThrow(); }); test("#readUInt8", () => { let buff = create<Buffer>([0xFE,0x0,0x0,0x0,0x2F]); // Testing casting between u8 and i8. expect(buff.readUInt8()).toBe(254); // Testing offset expect(buff.readUInt8(4)).toBe(47); expect(() => { let newBuff = new Buffer(1); newBuff.readUInt8(5); }).toThrow(); }); test("#writeInt8", () => { let buff = new Buffer(5); expect(buff.writeInt8(9)).toBe(1); expect(buff.writeInt8(-3,4)).toBe(5); let result = create<Buffer>([0x09, 0x0, 0x0, 0x0, 0xFD]); expect(buff).toStrictEqual(result); // TODO: expect(() => { let newBuff = new Buffer(1); newBuff.writeInt8(5,10); }).toThrow(); }); test("#writeUInt8", () => { let buff = new Buffer(5); expect(buff.writeUInt8(4)).toBe(1); expect(buff.writeUInt8(252,4)).toBe(5); let result = create<Buffer>([0x04, 0x0, 0x0, 0x0, 0xFC]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeUInt8(5,10); }).toThrow(); }); test("#readInt16LE", () => { let buff = create<Buffer>([0x0,0x05,0x0]); expect(buff.readInt16LE()).toBe(1280); expect(buff.readInt16LE(1)).toBe(5); expect(() => { let newBuff = new Buffer(1); newBuff.readInt16LE(0); }).toThrow(); }); test("#readInt16BE", () => { let buff = create<Buffer>([0x0,0x05,0x0]); expect(buff.readInt16BE()).toBe(5); expect(buff.readInt16BE(1)).toBe(1280); expect(() => { let newBuff = new Buffer(1); newBuff.readInt16BE(0); }).toThrow(); }); test("#readUInt16LE", () => { let buff = create<Buffer>([0x0,0x05,0x0]); expect(buff.readUInt16LE()).toBe(1280); expect(buff.readUInt16LE(1)).toBe(5); expect(() => { let newBuff = new Buffer(1); newBuff.readUInt16LE(0); }).toThrow(); }); test("#readUInt16BE", () => { let buff = create<Buffer>([0x0,0x05,0x0]); expect(buff.readUInt16BE()).toBe(5); expect(buff.readUInt16BE(1)).toBe(1280); expect(() => { let newBuff = new Buffer(1); newBuff.readUInt16BE(0); }).toThrow(); }); test("#writeInt16LE", () => { let buff = new Buffer(4); expect(buff.writeInt16LE(5)).toBe(2); expect(buff.writeInt16LE(1280,2)).toBe(4); let result = create<Buffer>([0x05, 0x0, 0x0, 0x5]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeInt16LE(0); }).toThrow(); }); test("#writeInt16BE", () => { let buff = new Buffer(4); expect(buff.writeInt16BE(1280)).toBe(2); expect(buff.writeInt16BE(5,2)).toBe(4); let result = create<Buffer>([0x05, 0x0, 0x0, 0x5]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeInt16BE(0); }).toThrow(); }); test("#writeUInt16LE", () => { let buff = new Buffer(4); expect(buff.writeUInt16LE(5)).toBe(2); expect(buff.writeUInt16LE(1280,2)).toBe(4); let result = create<Buffer>([0x05, 0x0, 0x0, 0x5]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeUInt16LE(0); }).toThrow(); }); test("#writeUInt16BE", () => { let buff = new Buffer(4); expect(buff.writeUInt16BE(1280)).toBe(2); expect(buff.writeUInt16BE(5,2)).toBe(4); let result = create<Buffer>([0x05, 0x0, 0x0, 0x5]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeUInt16BE(0); }).toThrow(); }); test("#readInt32LE", () => { let buff = create<Buffer>([0xEF,0xBE,0xAD,0xDE,0x0d,0xc0,0xde,0x10]); expect(buff.readInt32LE()).toBe(-559038737); expect(buff.readInt32LE(4)).toBe(283033613); expect(() => { let newBuff = new Buffer(1); newBuff.readInt32LE(0); }).toThrow(); }); test("#readInt32BE", () => { let buff = create<Buffer>([0xDE,0xAD,0xBE,0xEF,0x10,0xde,0xc0,0x0d]); expect(buff.readInt32BE()).toBe(-559038737); expect(buff.readInt32BE(4)).toBe(283033613); expect(() => { let newBuff = new Buffer(1); newBuff.readInt32BE(0); }).toThrow(); }); test("#readUInt32LE", () => { let buff = create<Buffer>([0xEF,0xBE,0xAD,0xDE,0x0d,0xc0,0xde,0x10]); expect(buff.readUInt32LE()).toBe(3735928559); expect(buff.readUInt32LE(4)).toBe(283033613); expect(() => { let newBuff = new Buffer(1); newBuff.readUInt32LE(0); }).toThrow(); }); test("#readUInt32BE", () => { let buff = create<Buffer>([0xDE,0xAD,0xBE,0xEF,0x10,0xde,0xc0,0x0d]); expect(buff.readUInt32BE()).toBe(3735928559); expect(buff.readUInt32BE(4)).toBe(283033613); expect(() => { let newBuff = new Buffer(1); newBuff.readUInt32BE(0); }).toThrow(); }); test("#writeInt32LE", () => { let buff = new Buffer(8); expect(buff.writeInt32LE(-559038737)).toBe(4); expect(buff.writeInt32LE(283033613,4)).toBe(8); let result = create<Buffer>([0xEF,0xBE,0xAD,0xDE,0x0d,0xc0,0xde,0x10]); expect<Buffer>(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeInt32LE(0); }).toThrow(); }); test("#writeInt32BE", () => { let buff = new Buffer(8); expect(buff.writeInt32BE(-559038737)).toBe(4); expect(buff.writeInt32BE(283033613,4)).toBe(8); let result = create<Buffer>([0xDE,0xAD,0xBE,0xEF,0x10,0xde,0xc0,0x0d]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeInt32BE(0); }).toThrow(); }); test("#writeUInt32LE", () => { let buff = new Buffer(8); expect(buff.writeUInt32LE(3735928559)).toBe(4); expect(buff.writeUInt32LE(283033613,4)).toBe(8); let result = create<Buffer>([0xEF,0xBE,0xAD,0xDE,0x0d,0xc0,0xde,0x10]);; expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeUInt32LE(0); }).toThrow(); }); test("#writeUInt32BE", () => { let buff = new Buffer(8); expect(buff.writeUInt32BE(3735928559)).toBe(4); expect(buff.writeUInt32BE(283033613,4)).toBe(8); let result = create<Buffer>([0xDE,0xAD,0xBE,0xEF,0x10,0xde,0xc0,0x0d]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeUInt32BE(0); }).toThrow(); }); test("#readFloatLE", () => { let buff = create<Buffer>([0xbb,0xfe,0x4a,0x4f,0x01,0x02,0x03,0x04]); expect(buff.readFloatLE()).toBe(0xcafebabe); expect(buff.readFloatLE(4)).toBe(1.539989614439558e-36); expect(() => { let newBuff = new Buffer(1); newBuff.readFloatLE(0); }).toThrow(); }); test("#readFloatBE", () => { let buff = create<Buffer>([0x4f,0x4a,0xfe,0xbb,0x01,0x02,0x03,0x04]); expect(buff.readFloatBE()).toBe(0xcafebabe); expect(buff.readFloatBE(4)).toBe(2.387939260590663e-38); expect(() => { let newBuff = new Buffer(1); newBuff.readFloatBE(0); }).toThrow(); }); test("#writeFloatLE", () => { let buff = new Buffer(8); expect(buff.writeFloatLE(0xcafebabe)).toBe(4); expect(buff.writeFloatLE(1.539989614439558e-36,4)).toBe(8); let result = create<Buffer>([0xbb,0xfe,0x4a,0x4f,0x01,0x02,0x03,0x04]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeFloatLE(0); }).toThrow(); }); test("#writeFloatBE", () => { let buff = new Buffer(8); expect(buff.writeFloatBE(0xcafebabe)).toBe(4); expect(buff.writeFloatBE(2.387939260590663e-38,4)).toBe(8); let result = create<Buffer>([0x4f,0x4a,0xfe,0xbb,0x01,0x02,0x03,0x04]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeFloatBE(0); }).toThrow(); }); test("#readBigInt64LE", () => { let buff = create<Buffer>([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00]); expect(buff.readBigInt64LE()).toBe(-4294967296); expect(buff.readBigInt64LE(8)).toBe(4294967295); expect(() => { let newBuff = new Buffer(1); newBuff.readBigInt64LE(0); }).toThrow(); }); test("#readBigInt64BE", () => { let buff = create<Buffer>([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00]); expect(buff.readBigInt64BE()).toBe(4294967295); expect(buff.readBigInt64BE(8)).toBe(-4294967296); expect(() => { let newBuff = new Buffer(1); newBuff.readBigInt64BE(0); }).toThrow(); }); test("#readBigUInt64LE", () => { let buff = create<Buffer>([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00]); expect(buff.readBigUInt64LE()).toBe(18446744069414584320); expect(buff.readBigUInt64LE(8)).toBe(4294967295); expect(() => { let newBuff = new Buffer(1); newBuff.readBigUInt64LE(0); }).toThrow(); }); test("#readBigUInt64BE", () => { let buff = create<Buffer>([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00]); expect(buff.readBigUInt64BE()).toBe(4294967295); expect(buff.readBigUInt64BE(8)).toBe(18446744069414584320); expect(() => { let newBuff = new Buffer(1); newBuff.readBigUInt64BE(0); }).toThrow(); }); test("#writeBigInt64LE", () => { let buff = new Buffer(16); expect(buff.writeBigInt64LE(-559038737)).toBe(8); expect(buff.writeBigInt64LE(283033613,8)).toBe(16); let result = create<Buffer>([0xEF,0xBE,0xAD,0xDE,0xFF,0xFF,0xFF,0xFF,0x0d,0xc0,0xde,0x10,0x00,0x00,0x00,0x00]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeBigInt64LE(0); }).toThrow(); }); test("#writeBigInt64BE", () => { let buff = new Buffer(16); expect(buff.writeBigInt64BE(-559038737)).toBe(8); expect(buff.writeBigInt64BE(283033613,8)).toBe(16); let result = create<Buffer>([0xFF,0xFF,0xFF,0xFF,0xDE,0xAD,0xBE,0xEF,0x00,0x00,0x00,0x00,0x10,0xde,0xc0,0x0d]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeBigInt64BE(0); }).toThrow(); }); test("#writeBigUInt64LE", () => { let buff = new Buffer(16); expect(buff.writeBigUInt64LE(3735928559)).toBe(8); expect(buff.writeBigUInt64LE(283033613,8)).toBe(16); let result = create<Buffer>([0xEF,0xBE,0xAD,0xDE,0x00,0x00,0x00,0x00,0x0d,0xc0,0xde,0x10,0x00,0x00,0x00,0x00]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeBigUInt64LE(0); }).toThrow(); }); test("#writeBigUInt64BE", () => { let buff = new Buffer(16); expect(buff.writeBigUInt64BE(3735928559)).toBe(8); expect(buff.writeBigUInt64BE(283033613,8)).toBe(16); let result = create<Buffer>([0x00,0x00,0x00,0x00,0xDE,0xAD,0xBE,0xEF,0x00,0x00,0x00,0x00,0x10,0xde,0xc0,0x0d]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeBigUInt64BE(0); }).toThrow(); }); test("#readDoubleLE", () => { let buff = create<Buffer>([0x77, 0xbe, 0x9f, 0x1a, 0x2f, 0xdd, 0x5e, 0x40, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]); expect(buff.readDoubleLE()).toBe(123.456); expect(buff.readDoubleLE(8)).toBe(5.447603722011605e-270); expect(() => { let newBuff = new Buffer(1); newBuff.readDoubleLE(0); }).toThrow(); }); test("#readDoubleBE", () => { let buff = create<Buffer>([0x40, 0x5e, 0xdd, 0x2f, 0x1a, 0x9f, 0xbe, 0x77, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]); expect(buff.readDoubleBE()).toBe(123.456); expect(buff.readDoubleBE(8)).toBe(8.20788039913184e-304); expect(() => { let newBuff = new Buffer(1); newBuff.readDoubleBE(0); }).toThrow(); }); test("#writeDoubleLE", () => { let buff = new Buffer(16); expect(buff.writeDoubleLE(123.456)).toBe(8); expect(buff.writeDoubleLE(5.447603722011605e-270,8)).toBe(16); let result = create<Buffer>([0x77, 0xbe, 0x9f, 0x1a, 0x2f, 0xdd, 0x5e, 0x40, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeDoubleLE(0); }).toThrow(); }); test("#writeDoubleBE", () => { let buff = new Buffer(16); expect(buff.writeDoubleBE(123.456)).toBe(8); expect(buff.writeDoubleBE(8.20788039913184e-304,8)).toBe(16); let result = create<Buffer>([0x40, 0x5e, 0xdd, 0x2f, 0x1a, 0x9f, 0xbe, 0x77, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]); expect(buff).toStrictEqual(result); expect(() => { let newBuff = new Buffer(1); newBuff.writeDoubleBE(0); }).toThrow(); }); test("#subarray", () => { let example = create<Buffer>([1, 2, 3, 4, 5, 6, 7, 8]); // no parameters means copy the Buffer let actual = example.subarray(); expect(actual).toStrictEqual(example); expect(actual.buffer).toBe(example.buffer); // should use the same buffer // start at offset 5 actual = example.subarray(5); let expected = create<Buffer>([6, 7, 8]); // trace("length", 1, expected.length); expect(actual).toStrictEqual(expected); // negative start indicies, start at (8 - 5) actual = example.subarray(-5); expected = create<Buffer>([4, 5, 6, 7, 8]); expect(actual).toStrictEqual(expected); // two parameters actual = example.subarray(2, 6); expected = create<Buffer>([3, 4, 5, 6]); expect(actual).toStrictEqual(expected); // negative end index actual = example.subarray(4, -1); expected = create<Buffer>([5, 6, 7]); expect(actual).toStrictEqual(expected); }); test("#swap16", () => { let actual = create<Buffer>([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); let expected = create<Buffer>([0x2, 0x1, 0x4, 0x3, 0x6, 0x5, 0x8, 0x7]); let swapped = actual.swap16(); expect(actual).toStrictEqual(expected); expect(swapped).toBe(actual); expect(() => { let newBuff = create<Buffer>([0x1, 0x2, 0x3]); newBuff.swap16(); }).toThrow(); }); test("#swap32", () => { let actual = create<Buffer>([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); let expected = create<Buffer>([0x4, 0x3, 0x2, 0x1, 0x8, 0x7, 0x6, 0x5]); let swapped = actual.swap32(); expect(actual).toStrictEqual(expected); expect(swapped).toBe(actual); expect(() => { let newBuff = create<Buffer>([0x1, 0x2, 0x3]); newBuff.swap64(); }).toThrow(); }); test("#swap64", () => { let actual = create<Buffer>([0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf]); let expected = create<Buffer>([0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8]); let swapped = actual.swap64(); expect(actual).toStrictEqual(expected); expect(swapped).toBe(actual); expect(() => { let newBuff = create<Buffer>([0x1, 0x2, 0x3]); newBuff.swap64(); }).toThrow(); }); test("#Hex.encode", () => { let actual = "000102030405060708090a0b0c0d0e0f102030405060708090a0b0c0d0e0f0"; let exampleBuffer = create<Buffer>([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0]); let encoded = Buffer.HEX.encode(actual); expect(encoded).toStrictEqual(exampleBuffer.buffer); }); test("#Hex.decode", () => { let expected = "000102030405060708090a0b0c0d0e0f102030405060708090a0b0c0d0e0f0"; let exampleBuffer = create<Buffer>([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0]); let decoded = Buffer.HEX.decode(exampleBuffer.buffer); expect(decoded).toStrictEqual(expected); }); test("#ASCII.encode", () => { let actual = "D34dB3eF"; let exampleBuffer = create<Buffer>([0x44, 0x33, 0x34, 0x64, 0x42, 0x33, 0x65, 0x46]); let encoded = Buffer.ASCII.encode(actual); expect(encoded).toStrictEqual(exampleBuffer.buffer); }); test("#ASCII.decode", () => { let expected = create<Buffer>([0x44, 0x33, 0x34, 0x64, 0x42, 0x33, 0x65, 0x46]); let example = "D34dB3eF"; let encoded = Buffer.ASCII.decode(expected.buffer); expect(encoded).toStrictEqual(example); }); });
the_stack
export type Maybe<T> = T | null; export enum MessageType { Location = "LOCATION", Text = "TEXT", Picture = "PICTURE" } /** A date-time string at UTC, such as 2007-12-03T10:15:30Z, compliant with the `date-time` format outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar. */ export type DateTime = any; // ==================================================== // Documents // ==================================================== export namespace AddChat { export type Variables = { userId: string; }; export type Mutation = { __typename?: "Mutation"; addChat: Maybe<AddChat>; }; export type AddChat = { __typename?: "Chat"; messages: (Maybe<Messages>)[]; } & ChatWithoutMessages.Fragment; export type Messages = Message.Fragment; } export namespace AddGroup { export type Variables = { userIds: string[]; groupName: string; }; export type Mutation = { __typename?: "Mutation"; addGroup: Maybe<AddGroup>; }; export type AddGroup = { __typename?: "Chat"; messages: (Maybe<Messages>)[]; } & ChatWithoutMessages.Fragment; export type Messages = Message.Fragment; } export namespace AddMessage { export type Variables = { chatId: string; content: string; }; export type Mutation = { __typename?: "Mutation"; addMessage: Maybe<AddMessage>; }; export type AddMessage = Message.Fragment; } export namespace ChatAdded { export type Variables = {}; export type Subscription = { __typename?: "Subscription"; chatAdded: Maybe<ChatAdded>; }; export type ChatAdded = { __typename?: "Chat"; messages: (Maybe<Messages>)[]; } & ChatWithoutMessages.Fragment; export type Messages = Message.Fragment; } export namespace GetChat { export type Variables = { chatId: string; }; export type Query = { __typename?: "Query"; chat: Maybe<Chat>; }; export type Chat = { __typename?: "Chat"; messages: (Maybe<Messages>)[]; } & ChatWithoutMessages.Fragment; export type Messages = Message.Fragment; } export namespace GetChats { export type Variables = { amount?: Maybe<number>; }; export type Query = { __typename?: "Query"; chats: Chats[]; }; export type Chats = { __typename?: "Chat"; messages: (Maybe<Messages>)[]; } & ChatWithoutMessages.Fragment; export type Messages = Message.Fragment; } export namespace GetUsers { export type Variables = {}; export type Query = { __typename?: "Query"; users: Maybe<Users[]>; }; export type Users = { __typename?: "User"; id: string; name: Maybe<string>; picture: Maybe<string>; }; } export namespace MessageAdded { export type Variables = {}; export type Subscription = { __typename?: "Subscription"; messageAdded: Maybe<MessageAdded>; }; export type MessageAdded = { __typename?: "Message"; chat: Chat; } & Message.Fragment; export type Chat = { __typename?: "Chat"; id: string; }; } export namespace RemoveAllMessages { export type Variables = { chatId: string; all?: Maybe<boolean>; }; export type Mutation = { __typename?: "Mutation"; removeMessages: Maybe<(Maybe<string>)[]>; }; } export namespace RemoveChat { export type Variables = { chatId: string; }; export type Mutation = { __typename?: "Mutation"; removeChat: Maybe<string>; }; } export namespace RemoveMessages { export type Variables = { chatId: string; messageIds?: Maybe<string[]>; }; export type Mutation = { __typename?: "Mutation"; removeMessages: Maybe<(Maybe<string>)[]>; }; } export namespace ChatWithoutMessages { export type Fragment = { __typename?: "Chat"; id: string; name: Maybe<string>; picture: Maybe<string>; allTimeMembers: AllTimeMembers[]; unreadMessages: number; isGroup: boolean; }; export type AllTimeMembers = { __typename?: "User"; id: string; }; } export namespace Message { export type Fragment = { __typename?: "Message"; id: string; chat: Chat; sender: Sender; content: string; createdAt: DateTime; type: number; recipients: Recipients[]; ownership: boolean; }; export type Chat = { __typename?: "Chat"; id: string; }; export type Sender = { __typename?: "User"; id: string; name: Maybe<string>; }; export type Recipients = { __typename?: "Recipient"; user: User; message: Message; chat: __Chat; receivedAt: Maybe<DateTime>; readAt: Maybe<DateTime>; }; export type User = { __typename?: "User"; id: string; }; export type Message = { __typename?: "Message"; id: string; chat: _Chat; }; export type _Chat = { __typename?: "Chat"; id: string; }; export type __Chat = { __typename?: "Chat"; id: string; }; } // ==================================================== // Scalars // ==================================================== // ==================================================== // Types // ==================================================== export interface Query { me?: Maybe<User>; users?: Maybe<User[]>; chats: Chat[]; chat?: Maybe<Chat>; } export interface User { id: string; name?: Maybe<string>; picture?: Maybe<string>; phone?: Maybe<string>; } export interface Chat { /** May be a chat or a group */ id: string; createdAt: DateTime; /** Computed for chats */ name?: Maybe<string>; /** Computed for chats */ picture?: Maybe<string>; /** All members, current and past ones. Includes users who still didn't get the chat listed. */ allTimeMembers: User[]; /** Whoever gets the chat listed. For groups includes past members who still didn't delete the group. For chats they are the only ones who can send messages. */ listingMembers: User[]; /** Actual members of the group. Null for chats. For groups they are the only ones who can send messages. They aren't the only ones who get the group listed. */ actualGroupMembers?: Maybe<User[]>; /** Null for chats */ admins?: Maybe<User[]>; /** If null the group is read-only. Null for chats. */ owner?: Maybe<User>; /** Computed property */ isGroup: boolean; messages: (Maybe<Message>)[]; /** Computed property */ lastMessage?: Maybe<Message>; /** Computed property */ updatedAt: DateTime; /** Computed property */ unreadMessages: number; } export interface Message { id: string; sender: User; chat: Chat; content: string; createdAt: DateTime; /** FIXME: should return MessageType */ type: number; /** Whoever still holds a copy of the message. Cannot be null because the message gets deleted otherwise */ holders: User[]; /** Computed property */ ownership: boolean; /** Whoever received the message */ recipients: Recipient[]; } export interface Recipient { user: User; message: Message; chat: Chat; receivedAt?: Maybe<DateTime>; readAt?: Maybe<DateTime>; } export interface Mutation { updateUser: User; addChat?: Maybe<Chat>; addGroup?: Maybe<Chat>; updateGroup?: Maybe<Chat>; removeChat?: Maybe<string>; addMessage?: Maybe<Message>; removeMessages?: Maybe<(Maybe<string>)[]>; addMembers?: Maybe<(Maybe<string>)[]>; removeMembers?: Maybe<(Maybe<string>)[]>; addAdmins?: Maybe<(Maybe<string>)[]>; removeAdmins?: Maybe<(Maybe<string>)[]>; setGroupName?: Maybe<string>; setGroupPicture?: Maybe<string>; markAsReceived?: Maybe<boolean>; markAsRead?: Maybe<boolean>; } export interface Subscription { messageAdded?: Maybe<Message>; chatAdded?: Maybe<Chat>; chatUpdated?: Maybe<Chat>; userUpdated?: Maybe<User>; userAdded?: Maybe<User>; } // ==================================================== // Arguments // ==================================================== export interface ChatQueryArgs { chatId: string; } export interface MessagesChatArgs { amount?: Maybe<number>; } export interface UpdateUserMutationArgs { name?: Maybe<string>; picture?: Maybe<string>; } export interface AddChatMutationArgs { userId: string; } export interface AddGroupMutationArgs { userIds: string[]; groupName: string; groupPicture?: Maybe<string>; } export interface UpdateGroupMutationArgs { chatId: string; groupName?: Maybe<string>; groupPicture?: Maybe<string>; } export interface RemoveChatMutationArgs { chatId: string; } export interface AddMessageMutationArgs { chatId: string; content: string; } export interface RemoveMessagesMutationArgs { chatId: string; messageIds?: Maybe<(Maybe<string>)[]>; all?: Maybe<boolean>; } export interface AddMembersMutationArgs { groupId: string; userIds: string[]; } export interface RemoveMembersMutationArgs { groupId: string; userIds: string[]; } export interface AddAdminsMutationArgs { groupId: string; userIds: string[]; } export interface RemoveAdminsMutationArgs { groupId: string; userIds: string[]; } export interface SetGroupNameMutationArgs { groupId: string; } export interface SetGroupPictureMutationArgs { groupId: string; } export interface MarkAsReceivedMutationArgs { chatId: string; } export interface MarkAsReadMutationArgs { chatId: string; } export interface MessageAddedSubscriptionArgs { chatId?: Maybe<string>; } // ==================================================== // START: Apollo Angular template // ==================================================== import { Injectable } from "@angular/core"; import * as Apollo from "apollo-angular"; import gql from "graphql-tag"; // ==================================================== // GraphQL Fragments // ==================================================== export const ChatWithoutMessagesFragment = gql` fragment ChatWithoutMessages on Chat { id name picture allTimeMembers { id } unreadMessages isGroup } `; export const MessageFragment = gql` fragment Message on Message { id chat { id } sender { id name } content createdAt type recipients { user { id } message { id chat { id } } chat { id } receivedAt readAt } ownership } `; // ==================================================== // Apollo Services // ==================================================== @Injectable({ providedIn: "root" }) export class AddChatGQL extends Apollo.Mutation< AddChat.Mutation, AddChat.Variables > { document: any = gql` mutation AddChat($userId: ID!) { addChat(userId: $userId) { ...ChatWithoutMessages messages { ...Message } } } ${ChatWithoutMessagesFragment} ${MessageFragment} `; } @Injectable({ providedIn: "root" }) export class AddGroupGQL extends Apollo.Mutation< AddGroup.Mutation, AddGroup.Variables > { document: any = gql` mutation AddGroup($userIds: [ID!]!, $groupName: String!) { addGroup(userIds: $userIds, groupName: $groupName) { ...ChatWithoutMessages messages { ...Message } } } ${ChatWithoutMessagesFragment} ${MessageFragment} `; } @Injectable({ providedIn: "root" }) export class AddMessageGQL extends Apollo.Mutation< AddMessage.Mutation, AddMessage.Variables > { document: any = gql` mutation AddMessage($chatId: ID!, $content: String!) { addMessage(chatId: $chatId, content: $content) { ...Message } } ${MessageFragment} `; } @Injectable({ providedIn: "root" }) export class ChatAddedGQL extends Apollo.Subscription< ChatAdded.Subscription, ChatAdded.Variables > { document: any = gql` subscription chatAdded { chatAdded { ...ChatWithoutMessages messages { ...Message } } } ${ChatWithoutMessagesFragment} ${MessageFragment} `; } @Injectable({ providedIn: "root" }) export class GetChatGQL extends Apollo.Query<GetChat.Query, GetChat.Variables> { document: any = gql` query GetChat($chatId: ID!) { chat(chatId: $chatId) { ...ChatWithoutMessages messages { ...Message } } } ${ChatWithoutMessagesFragment} ${MessageFragment} `; } @Injectable({ providedIn: "root" }) export class GetChatsGQL extends Apollo.Query< GetChats.Query, GetChats.Variables > { document: any = gql` query GetChats($amount: Int) { chats { ...ChatWithoutMessages messages(amount: $amount) { ...Message } } } ${ChatWithoutMessagesFragment} ${MessageFragment} `; } @Injectable({ providedIn: "root" }) export class GetUsersGQL extends Apollo.Query< GetUsers.Query, GetUsers.Variables > { document: any = gql` query GetUsers { users { id name picture } } `; } @Injectable({ providedIn: "root" }) export class MessageAddedGQL extends Apollo.Subscription< MessageAdded.Subscription, MessageAdded.Variables > { document: any = gql` subscription messageAdded { messageAdded { ...Message chat { id } } } ${MessageFragment} `; } @Injectable({ providedIn: "root" }) export class RemoveAllMessagesGQL extends Apollo.Mutation< RemoveAllMessages.Mutation, RemoveAllMessages.Variables > { document: any = gql` mutation RemoveAllMessages($chatId: ID!, $all: Boolean) { removeMessages(chatId: $chatId, all: $all) } `; } @Injectable({ providedIn: "root" }) export class RemoveChatGQL extends Apollo.Mutation< RemoveChat.Mutation, RemoveChat.Variables > { document: any = gql` mutation RemoveChat($chatId: ID!) { removeChat(chatId: $chatId) } `; } @Injectable({ providedIn: "root" }) export class RemoveMessagesGQL extends Apollo.Mutation< RemoveMessages.Mutation, RemoveMessages.Variables > { document: any = gql` mutation RemoveMessages($chatId: ID!, $messageIds: [ID!]) { removeMessages(chatId: $chatId, messageIds: $messageIds) } `; } // ==================================================== // END: Apollo Angular template // ====================================================
the_stack
"use strict"; /* * Copyright (C) 1998-2018 by Northwoods Software Corporation. All Rights Reserved. */ import * as go from "../release/go"; /** * @constructor * @extends Tool * @class * This GeometryReshapingTool class allows for a Shape's Geometry to be modified by the user * via the dragging of tool handles. * This does not handle Links, whose routes should be reshaped by the LinkReshapingTool. * The {@link #reshapeObjectName} needs to identify the named {@link Shape} within the * selected {@link Part}. * If the shape cannot be found or if its {@link Shape#geometry} is not of type {@link Geometry#Path}, * this will not show any GeometryReshaping {@link Adornment}. * At the current time this tool does not support adding or removing {@link PathSegment}s to the Geometry. */ export class GeometryReshapingTool extends go.Tool { /** @type {GraphObject} */ private _handleArchetype: go.GraphObject; constructor() { super(); const h: go.Shape = new go.Shape(); h.figure = "Diamond"; h.desiredSize = new go.Size(7, 7); h.fill = "lightblue"; h.stroke = "dodgerblue"; h.cursor = "move"; this._handleArchetype = h; this.name = "GeometryReshaping"; } /** @type {string} */ private _reshapeObjectName = 'SHAPE'; //??? can't add Part.reshapeObjectName property // there's no Part.reshapeAdornmentTemplate either // internal state /** @type {GraphObject} */ private _handle: go.GraphObject | null = null; /** @type {Shape} */ private _adornedShape: go.Shape | null = null; /** @type {Geometry} */ private _originalGeometry: go.Geometry | null = null; // in case the tool is cancelled and the UndoManager is not enabled /** * A small GraphObject used as a reshape handle for each segment. * The default GraphObject is a small blue diamond. * @name GeometryReshapingTool#handleArchetype * @function. * @return {GraphObject} */ get handleArchetype(): go.GraphObject { return this._handleArchetype } set handleArchetype(value: go.GraphObject) { this._handleArchetype = value } /** * The name of the GraphObject to be reshaped. * @name GeometryReshapingTool#reshapeObjectName * @function. * @return {string} */ get reshapeObjectName(): string { return this._reshapeObjectName } set reshapeObjectName(value: string) { this._reshapeObjectName = value } /** * This read-only property returns the {@link GraphObject} that is the tool handle being dragged by the user. * This will be contained by an {@link Adornment} whose category is "GeometryReshaping". * Its {@link Adornment#adornedObject} is the same as the {@link #adornedShape}. * @name GeometryReshapingTool#handle * @function. * @return {GraphObject} */ get handle(): go.GraphObject | null { return this._handle } /** * Gets the {@link Shape} that is being reshaped. * This must be contained within the selected Part. * @name GeometryReshapingTool#adornedShape * @function. * @return {Shape} */ get adornedShape(): go.Shape | null { return this._adornedShape } /** * This read-only property remembers the original value for {@link Shape#geometry}, * so that it can be restored if this tool is cancelled. * @name GeometryReshapingTool#originalGeometry * @function. * @return {Geometry} */ get originalGeometry(): go.Geometry | null { return this._originalGeometry } /** * Show an {@link Adornment} with a reshape handle at each point of the geometry. * Don't show anything if {@link #reshapeObjectName} doesn't identify a {@link Shape} * that has a {@link Shape#geometry} of type {@link Geometry#Path}. * @this {GeometryReshapingTool} * @param {Part} part the part. */ public updateAdornments(part: go.Part) { if (part === null || part instanceof go.Link) return; // this tool never applies to Links if (part.isSelected && !this.diagram.isReadOnly) { var selelt = part.findObject(this.reshapeObjectName); if (selelt instanceof go.Shape && selelt.actualBounds.isReal() && selelt.isVisibleObject() && part.canReshape() && part.actualBounds.isReal() && part.isVisible() && selelt.geometry.type === go.Geometry.Path) { var adornment = part.findAdornment(this.name); if (adornment === null) { adornment = this.makeAdornment(selelt); } if (adornment !== null) { // update the position/alignment of each handle var geo = selelt.geometry; var b = geo.bounds; // update the size of the adornment adornment.findObject("BODY").desiredSize = b.size; adornment.elements.each(function (h: any) { if (h._typ === undefined) return; var fig = geo.figures.elt(h._fig); var seg = fig.segments.elt(h._seg); var x = 0; var y = 0; switch (h._typ) { case 0: x = fig.startX; y = fig.startY; break; case 1: x = seg.endX; y = seg.endY; break; case 2: x = seg.point1X; y = seg.point1Y; break; case 3: x = seg.point2X; y = seg.point2Y; break; } var bw = b.width; if (bw === 0) bw = 0.001; var bh = b.height; if (bh === 0) bh = 0.001; h.alignment = new go.Spot(Math.max(0, Math.min((x - b.x) / bw, 1)), Math.max(0, Math.min((y - b.y) / bh, 1))); }); part.addAdornment(this.name, adornment); adornment.location = selelt.getDocumentPoint(go.Spot.TopLeft); adornment.angle = selelt.getDocumentAngle(); return; } } } part.removeAdornment(this.name); }; /** * @this {GeometryReshapingTool} */ public makeAdornment(selelt: go.Shape) { var adornment = new go.Adornment(); adornment.type = go.Panel.Spot; adornment.locationObjectName = "BODY"; adornment.locationSpot = new go.Spot(0, 0, -selelt.strokeWidth / 2, -selelt.strokeWidth / 2); var h: any = new go.Shape(); h.name = "BODY"; h.fill = null; h.stroke = null; h.strokeWidth = 0; adornment.add(h); var geo = selelt.geometry; // requires Path Geometry, checked above in updateAdornments for (var f = 0; f < geo.figures.count; f++) { var fig = geo.figures.elt(f); for (var g = 0; g < fig.segments.count; g++) { var seg = fig.segments.elt(g); var h; if (g === 0) { h = this.makeHandle(selelt, fig, seg); if (h !== null) { h._typ = 0; h._fig = f; h._seg = g; adornment.add(h); } } h = this.makeHandle(selelt, fig, seg); if (h !== null) { h._typ = 1; h._fig = f; h._seg = g; adornment.add(h); } if (seg.type === go.PathSegment.QuadraticBezier || seg.type === go.PathSegment.Bezier) { h = this.makeHandle(selelt, fig, seg); if (h !== null) { h._typ = 2; h._fig = f; h._seg = g; adornment.add(h); } if (seg.type === go.PathSegment.Bezier) { h = this.makeHandle(selelt, fig, seg); if (h !== null) { h._typ = 3; h._fig = f; h._seg = g; adornment.add(h); } } } } } adornment.category = this.name; adornment.adornedObject = selelt; return adornment; }; /** * @this {GeometryReshapingTool} */ public makeHandle(selelt: go.GraphObject, fig: go.PathFigure, seg: go.PathSegment) { var h = this.handleArchetype; if (h === null) return null; return h.copy(); }; /** * @this {GeometryReshapingTool} */ public canStart(): boolean { if (!this.isEnabled) return false; var diagram = this.diagram; if (diagram === null || diagram.isReadOnly) return false; if (!diagram.allowReshape) return false; if (!diagram.lastInput.left) return false; var h = this.findToolHandleAt(diagram.firstInput.documentPoint, this.name); return (h !== null); }; /** * @this {GeometryReshapingTool} */ public doActivate() { var diagram = this.diagram; if (diagram === null) return; this._handle = this.findToolHandleAt(diagram.firstInput.documentPoint, this.name); if (this._handle === null) return; var shape = (this.handle.part as go.Adornment).adornedObject as go.Shape; if (!shape) return; this._adornedShape = shape; diagram.isMouseCaptured = true; this.startTransaction(this.name); this._originalGeometry = shape.geometry; this.isActive = true; }; /** * @this {GeometryReshapingTool} */ public doDeactivate() { this.stopTransaction(); this._handle = null; this._adornedShape = null; var diagram = this.diagram; if (diagram !== null) diagram.isMouseCaptured = false; this.isActive = false; }; /** * @this {GeometryReshapingTool} */ public doCancel() { var shape = this._adornedShape; if (shape !== null) { // explicitly restore the original route, in case !UndoManager.isEnabled shape.geometry = this._originalGeometry; } this.stopTool(); }; /** * @this {GeometryReshapingTool} */ public doMouseMove() { var diagram = this.diagram; if (this.isActive && diagram !== null) { var newpt = this.computeReshape(diagram.lastInput.documentPoint); this.reshape(newpt); } }; /** * @this {GeometryReshapingTool} */ public doMouseUp() { var diagram = this.diagram; if (this.isActive && diagram !== null) { var newpt = this.computeReshape(diagram.lastInput.documentPoint); this.reshape(newpt); this.transactionResult = this.name; // success } this.stopTool(); }; /** * @expose * @this {GeometryReshapingTool} * @param {Point} newPoint the value of the call to {@link #computeReshape}. */ public reshape(newPoint: go.Point) { var shape = this.adornedShape; var locpt = shape.getLocalPoint(newPoint); var geo = shape.geometry.copy(); shape.desiredSize = new go.Size(NaN, NaN); // set the desiredSize once we've gotten our Geometry so we don't clobber var type = (this.handle as any)._typ; if (type === undefined) return; var fig = geo.figures.elt((this.handle as any)._fig); var seg = fig.segments.elt((this.handle as any)._seg); switch (type) { case 0: fig.startX = locpt.x; fig.startY = locpt.y; break; case 1: seg.endX = locpt.x; seg.endY = locpt.y; break; case 2: seg.point1X = locpt.x; seg.point1Y = locpt.y; break; case 3: seg.point2X = locpt.x; seg.point2Y = locpt.y; break; } var offset = geo.normalize(); // avoid any negative coordinates in the geometry shape.geometry = geo; // modify the Shape var part = shape.part; // move the Part holding the Shape if (!part.locationSpot.equals(go.Spot.Center)) { // but only if the locationSpot isn't Center part.move(part.position.copy().subtract(offset)); } this.updateAdornments(part); // update any Adornments of the Part this.diagram.maybeUpdate(); // force more frequent drawing for smoother looking behavior }; /** * @expose * @this {GeometryReshapingTool} * @param {Point} p the point where the handle is being dragged. * @return {Point} */ public computeReshape(p: go.Point) { return p; // no constraints on the points }; }
the_stack
import { // Badge, Heading, Text, Stack, Button, Stat, StatHelpText, // StatLabel, StatNumber, Box, } from "@chakra-ui/react"; import NextLink from "next/link"; import * as React from "react"; export const data = [ { type: "header", description: <Box minW="12em" />, free: ( <Stack> <Heading>Free</Heading> <Text fontWeight="normal"> Ideal for testing the platform with smaller volumes and limited workforce </Text> </Stack> ), starter: ( <Stack> <Heading>Starter</Heading> <Text fontWeight="normal"> Ideal for self-service mid-size projects with limited workforce </Text> </Stack> ), pro: ( <Stack> <Heading>Pro</Heading> <Text fontWeight="normal"> Ideal for large volume projects with no set cycle and one-time ML tasks </Text> </Stack> ), enterprise: ( <Stack> <Heading>Enterprise</Heading> <Text fontWeight="normal"> Best for well-established, strategically defined projects with recurring high-volume tasks </Text> </Stack> ), }, { description: "Price", free: ( <Stat> <StatNumber>$0</StatNumber> <StatHelpText>/month</StatHelpText> </Stat> ), starter: ( <Stat> <StatNumber>$59</StatNumber> <StatHelpText>/month/user</StatHelpText> </Stat> ), pro: ( <NextLink href="/request-access"> <Button>Request a demo</Button> </NextLink> ), enterprise: ( <NextLink href="/request-access"> <Button>Contact us</Button> </NextLink> ), }, { description: "Free period", free: ( <Stat> <StatNumber>Forever</StatNumber> <StatHelpText>Free</StatHelpText> </Stat> ), starter: ( <Stat> <StatNumber>14 days</StatNumber> <StatHelpText>Free trial</StatHelpText> </Stat> ), pro: ( <Stat> <StatNumber>14 days</StatNumber> <StatHelpText>Free trial</StatHelpText> </Stat> ), enterprise: ( <NextLink href="/request-access"> <Button>Contact us</Button> </NextLink> ), }, { description: "Number of users", free: "up to 5", starter: "up to 25", pro: "unlimited", enterprise: "unlimited", }, { description: "Number of images", free: "up to 100/month", starter: "up to 10,000/month", pro: "unlimited", enterprise: "unlimited", }, { type: "sectionHeader", description: "Label and annotate images", free: "", starter: "", pro: "", enterprise: "", }, { description: ( <> <Text>Classification editor</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> simply apply labels to whole image </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Vector editor</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> detection bounding box, polygon, ellipse, polyline, keypoints, templates, etc. </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Pixel editor</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> semantic and panoptic segmentation </Text> </> ), free: "soon", starter: "soon", pro: "soon", enterprise: "soon", }, { description: ( <> <Text>Video support</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> videos with tracking of detections between frames </Text> </> ), free: "up to 100 frames", starter: "up to 100 frames", pro: true, enterprise: true, }, { description: ( <> <Text>Tiled imagery support</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> geospatial images, maps, orthophotos, large-scale non-gis images, etc. </Text> </> ), free: "up to 10 images", starter: "up to 10 images", pro: true, enterprise: true, }, { type: "sectionHeader", description: "Integrate your data and tools easily", free: "", starter: "", pro: "", enterprise: "", }, { description: ( <> <Text>Dataset import</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> COCO, Yolo, ImageNet, TFrecord, CSV, PASCAL VOC, etc. </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Dataset export</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> COCO, Yolo, ImageNet, TFrecord, CSV, PASCAL VOC, etc. </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>API access</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> GraphQL and HTTP Rest API </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>SDK access</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Python SDK, Typescript and Javascript SDK </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Pluggable storage</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Amazon S3, Google Cloud Storage, Azure Blob storage, Minio, etc. </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Pluggable database</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> PostgreSQL, MySQL, Snowflake, BigQuery, AWS Redshift, etc. </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Zapier connector</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Connect with 3000+ tools </Text> </> ), free: false, starter: false, pro: "soon", enterprise: "soon", }, { type: "sectionHeader", description: "Manage your data pipelines seamlessly", free: "", starter: "", pro: "", enterprise: "", }, { description: ( <> <Text>Projects management</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Organize in projects, folders and files </Text> </> ), // description: "Project management", free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>User roles</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> QC roles, role-based access control, authorizations, etc. </Text> </> ), // description: "User roles", free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Auto Workflows</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Quality management, automatic task distribution, consensus, benchmarks, review labels, etc. </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Workflow editor</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Workflow editor with custom steps </Text> </> ), free: false, starter: false, pro: "soon", enterprise: "soon", }, { type: "sectionHeader", description: "Get smart help for your labeling tasks", free: "", starter: "", pro: "", enterprise: "", }, { description: ( <> <Text>Smart labeling tools</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Label faster thanks to advanced computer-vision-based tools </Text> </> ), free: false, starter: "soon", pro: "soon", enterprise: "soon", }, { description: ( <> <Text>Pre labeling</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Get your images pre-labeled by your AI or our AI </Text> </> ), free: false, starter: "soon", pro: "soon", enterprise: "soon", }, { description: ( <> <Text>Your AI in the loop</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Have your AI assist your labeling and learn continuously </Text> </> ), free: false, starter: "soon", pro: "soon", enterprise: "soon", }, { description: ( <> <Text>Active learning</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Label in priority images that your AI is confused about </Text> </> ), free: false, starter: "soon", pro: "soon", enterprise: "soon", }, { description: ( <> <Text>Humans labeling marketplace</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Get real humans in the loop through our marketplace </Text> </> ), free: false, starter: "soon", pro: "soon", enterprise: "soon", }, { type: "sectionHeader", description: "Analyze performance and get insights", free: "", starter: "", pro: "", enterprise: "", }, { description: ( <> <Text>Annotator Analytics</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Dashboards to analyze performance and quality of annotators </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Task Analytics</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Analyze your labeling tasks, identify hard ones and better plan campaigns </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Dataset Analytics</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Analyze datasets and models, identify issues in your datasets </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { type: "sectionHeader", description: "Own your data and ensure compliance and security", free: "", starter: "", pro: "", enterprise: "", }, { description: ( <> <Text>Fully compliant solution</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> SOC II, ISO 27001 compliance </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>On-premise backend</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Fully on-premise and airgapped image store and database. No data goes through LabelFlow servers </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>White label deployment</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Deploy LabelFlow as part of your solution. JS components and server. </Text> </> ), free: false, starter: false, pro: "add-on", enterprise: "add-on", }, { description: ( <> <Text>On-premise frontend</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Fully on-premise or airgapped deployment of the entire solution </Text> </> ), free: false, starter: false, pro: false, enterprise: "soon", }, { description: ( <> <Text>Single Sign On</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> SSO, SAML, and Enterprise authentication features </Text> </> ), free: false, starter: false, pro: false, enterprise: "soon", }, { description: ( <> <Text>Compliance Controls</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> PII and GDPR data controls, Audit logs visibility on all account activity </Text> </> ), free: false, starter: false, pro: false, enterprise: "soon", }, { type: "sectionHeader", description: "Get support and access the community", free: "", starter: "", pro: "", enterprise: "", }, { description: ( <> <Text>Public community</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Github issues and discussions </Text> </> ), free: true, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Community</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Access to a vibrant community on Slack </Text> </> ), free: false, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Basic support</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Chat and email support </Text> </> ), free: false, starter: true, pro: true, enterprise: true, }, { description: ( <> <Text>Humans labeling marketplace</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Get human workers to help label your data </Text> </> ), free: false, starter: "soon", pro: "soon", enterprise: "soon", }, { description: ( <> <Text>Advanced support</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Slack channel, dedicated success manager and engineers </Text> </> ), free: false, starter: false, pro: true, enterprise: true, }, { description: ( <> <Text>Enterprise support</Text> <Text fontSize="xs" lineHeight="1" color="gray.500"> Dedicated ML engineer and consulting to ensure smooth operation </Text> </> ), free: false, starter: false, pro: false, enterprise: true, }, { type: "header", description: <Box minW="12em" />, free: ( <Stack> <Heading>Free</Heading> {/* <Text fontWeight="normal"> Ideal for testing the platform with smaller volumes and limited workforce </Text> */} </Stack> ), starter: ( <Stack> <Heading>Starter</Heading> {/* <Text fontWeight="normal"> Ideal for self-service mid-size projects with limited workforce </Text> */} </Stack> ), pro: ( <Stack> <Heading>Pro</Heading> {/* <Text fontWeight="normal"> Ideal for large volume projects with no set cycle and one-time ML tasks </Text> */} </Stack> ), enterprise: ( <Stack> <Heading>Enterprise</Heading> {/* <Text fontWeight="normal"> Best for well-established, strategically defined projects with recurring high-volume tasks </Text> */} </Stack> ), }, { type: "header", description: <Box minW="12em" />, free: ( <NextLink href="/local/datasets"> <Button colorScheme="brand">Try it now</Button> </NextLink> ), starter: ( <NextLink href="/request-access"> <Button colorScheme="brand">Request Access</Button> </NextLink> ), pro: ( <NextLink href="/request-access"> <Button colorScheme="brand">Request a demo</Button> </NextLink> ), enterprise: ( <NextLink href="/request-access"> <Button colorScheme="brand">Contact us</Button> </NextLink> ), }, ]; export const columns = [ { accessor: "description", }, { accessor: "free", }, { accessor: "starter", }, { accessor: "pro", }, { accessor: "enterprise", }, ];
the_stack
import { Injectable } from '@angular/core'; import { Plugin, Cordova, CordovaProperty, CordovaInstance, InstanceProperty, IonicNativePlugin } from '@ionic-native/core'; import { Observable } from 'rxjs'; export interface JMSingleType { type: 'single'; username: string; appKey?: string; }; export interface JMGroupType { type: 'group'; groupId: string; }; export interface JMChatRoomType { type: 'chatRoom'; roomId: string; }; export type JMAllType = (JMSingleType | JMGroupType | JMChatRoomType); export interface JMMessageOptions { extras?: { [key: string]: string; }; messageSendingOptions?: JMMessageSendOptions; }; export interface JMConfig { isOpenMessageRoaming: boolean; }; export interface JMError { code: string; description: string; }; /** * Message type */ export interface JMNormalMessage { id: string; // 本地数据库中的消息 id serverMessageId: string; // 对应服务器端的消息 id isSend: boolean; // 消息是否由当前用户发出。true:为当前用户发送;false:为对方用户发送。 from: JMUserInfo; // 消息发送者对象 target: (JMUserInfo | JMGroupInfo); // 消息接收者对象 createTime: number; // 发送消息时间 extras?: { [key: string]: string; }; // 附带的键值对 }; export type JMTextMessage = JMNormalMessage & { type: 'text'; text: string; // 消息内容 }; export type JMVoiceMessage = JMNormalMessage & { type: 'voice'; path?: string; // 语音文件路径,如果为空需要调用相应下载方法 duration: number; // 语音时长,单位秒 }; export type JMImageMessage = JMNormalMessage & { type: 'image'; thumbPath?: string; // 图片的缩略图路径, 如果为空需要调用相应下载方法 }; export type JMFileMessage = JMNormalMessage & { type: 'file'; fileName: string; // 文件名 }; export type JMLocationMessage = JMNormalMessage & { type: 'location'; longitude: number; // 经度 latitude: number; // 纬度 scale: number; // 地图缩放比例 address?: string; // 详细地址 }; export type JMCustomMessage = JMNormalMessage & { type: 'custom'; customObject: { [key: string]: string; } // 自定义键值对 }; export interface JMEventMessage { type: 'event'; // 消息类型 eventType: 'group_member_added' | 'group_member_removed' | 'group_member_exit'; // 'group_member_added' / 'group_member_removed' / 'group_member_exit' usernames: string[]; // 该事件涉及到的用户 username 数组 }; export type JMAllMessage = JMTextMessage | JMVoiceMessage | JMImageMessage | JMFileMessage | JMEventMessage | JMCustomMessage; export type JMMessageEventListener = (message: JMAllMessage) => void; export type JMSyncOfflineMessageListener = (event: { conversation: JMConversationInfo; messageArray: JMAllMessage[]; }) => void; export type JMSyncRoamingMessageListener = (event: { conversation: JMConversationInfo; }) => void; export type JMLoginStateChangedListener = (event: { type: 'user_password_change' | 'user_logout' | 'user_deleted' | 'user_login_status_unexpected'; }) => void; export type JMContactNotifyListener = (event: { type: 'invite_received' | 'invite_accepted' | 'invite_declined' | 'contact_deleted'; reason: string; fromUsername: string; fromUserAppKey?: string; }) => void; export type JMMessageRetractListener = (event: { conversation: JMConversationInfo; retractedMessage: JMAllMessage; }) => void; export type JMReceiveTransCommandListener = (event: { message: string; sender: JMUserInfo; receiver: JMUserInfo | JMGroupInfo; receiverType: 'single' | 'group'; }) => void; export type JMReceiveChatRoomMessageListener = (event: { messageArray: JMAllMessage[]; }) => void; export type JMReceiveApplyJoinGroupApprovalListener = (event: { eventId: string; groupId: string; isInitiativeApply: boolean; sendApplyUser: JMUserInfo; joinGroupUsers?: JMUserInfo[]; reason?: string; }) => void; export type JMReceiveGroupAdminRejectListener = (event: { groupId: string; groupManager: JMUserInfo; reason?: string; }) => void; export type JMReceiveGroupAdminApprovalListener = (event: { isAgree: boolean; applyEventId: string; groupId: string; groupAdmin: JMUserInfo; users: JMUserInfo[]; }) => void; /** * User Type */ export interface JMUserInfo { type: 'user'; username: string; // 用户名 appKey?: string; // 用户所属应用的 appKey,可与 username 共同作为用户的唯一标识 nickname?: string; // 昵称 gender: 'male' | 'female' | 'unknown'; // 'male' / 'female' / 'unknown' avatarThumbPath: string; // 头像的缩略图地址 birthday?: number; // 日期的毫秒数 region?: string; // 地区 signature?: string; // 个性签名 address?: string; // 具体地址 noteName?: string; // 备注名 noteText?: string; // 备注信息 isNoDisturb: boolean; // 是否免打扰 isInBlackList: boolean; // 是否在黑名单中 isFriend: boolean; // 是否为好友 extras?: { [key: string]: string; }; // 自定义键值对 }; export interface JMGroupMemberInfo { user: JMUserInfo; // 群用户详情 groupNickname: string; // 用户的群昵称 memberType: 'owner' | 'admin' | 'ordinary'; // 用户类型 joinGroupTime: number; // 用户入群时间(单位:毫秒) } export interface JMGroupInfo { type: 'group'; id: string; // 群组 id name?: string; // 群组名称 desc?: string; // 群组描述 level: number; // 群组等级,默认等级 4 owner: string; // 群主的 username ownerAppKey?: string; // 群主的 appKey maxMemberCount: number; // 最大成员数 isNoDisturb: boolean; // 是否免打扰 isBlocked: boolean; // 是否屏蔽群消息 }; export interface JMChatRoomInfo { type: 'chatRoom'; roomId: string; // 聊天室 id name: string; // 聊天室名称 appKey?: string; // 聊天室所属应用的 App Key description?: string; // 聊天室描述信息 createTime: number; // 创建日期,单位:秒 maxMemberCount?: number; // 最大成员数 memberCount: number; // 当前成员数 }; export type JMConversationInfo = ({ conversationType: 'single'; target: JMUserInfo; } | { conversationType: 'group'; target: JMGroupInfo; }) & { title: string; // 会话标题 latestMessage: JMAllMessage; // 最近的一条消息对象。如果不存在消息,则 conversation 对象中没有该属性。 unreadCount: number; // 未读消息数 }; export interface JMMessageSendOptions { /** * 接收方是否针对此次消息发送展示通知栏通知。 * @type {boolean} * @defaultvalue */ isShowNotification?: boolean; /** * 是否让后台在对方不在线时保存这条离线消息,等到对方上线后再推送给对方。 * @type {boolean} * @defaultvalue */ isRetainOffline?: boolean; /** * 是否开启了自定义接收方通知栏功能。 * @type {?boolean} */ isCustomNotificationEnabled?: boolean; /** * 设置此条消息在接收方通知栏所展示通知的标题。 * @type {?string} */ notificationTitle?: string; /** * 设置此条消息在接收方通知栏所展示通知的内容。 * @type {?string} */ notificationText?: string; }; // TODO: to Promise @Injectable({ providedIn: 'root' }) export class JMChatRoom { @Cordova() getChatRoomInfoListOfApp(params: { start: number; count: number; }, success: (chatroomList: JMChatRoomInfo[]) => void, fail: (error: JMError) => void): void {} @Cordova() getChatRoomInfoListOfUser( success: (chatroomList: JMChatRoomInfo[]) => void, fail: (error: JMError) => void): void {} @Cordova() getChatRoomInfoListById(params: { roomId: string; }, success: (chatroomList: JMChatRoomInfo[]) => void, fail: (error: JMError) => void): void {} @Cordova() getChatRoomOwner(params: { roomId: string; }, success: (chatroomList: JMUserInfo) => void, fail: (error: JMError) => void): void {} @Cordova() enterChatRoom(obj: { roomId: string; }, success: (conversation: JMConversationInfo) => void, fail: (error: JMError) => void): void {} @Cordova() exitChatRoom(params: { roomId: string; }, success: () => void, fail: (error: JMError) => void): void {} @Cordova() getChatRoomConversation(params: { roomId: string; }, success: () => void, fail: (error: JMError) => void): void {} @Cordova() getChatRoomConversationList(success: (conversationList: JMConversationInfo[]) => void, fail: (error: JMError) => void): void {} } @Plugin({ pluginName: 'JMessagePlugin', plugin: 'jmessage-phonegap-plugin', pluginRef: 'JMessage', repo: 'https://github.com/jpush/jmessage-phonegap-plugin', install: 'cordova plugin add jmessage-phonegap-plugin --variable APP_KEY=your_app_key', // OPTIONAL install command, in case the plugin requires variables installVariables: ['APP_KEY'], platforms: ['Android', 'iOS'] }) @Injectable({ providedIn: 'root' }) export class JMessagePlugin extends IonicNativePlugin { /** * This function does something * @param arg1 {string} Some param to configure something * @param arg2 {number} Another param to configure something * @return {Promise<any>} Returns a promise that resolves when something happens */ @Cordova() functionName(arg1: string, arg2: number): Promise<any> { return; // We add return; here to avoid any IDE / Compiler errors } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) init(params: JMConfig): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) setDebugMode(params: { enable: boolean; }): void {} @Cordova() register(params: { username: string; password: string; nickname: string; }): Promise<void> { return; } @Cordova() login(params: { username: string; password: string; }): Promise<void> { return; } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) logout(): void {} @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) setBadge(params: { badge: number; }): void { } @Cordova() getMyInfo(): Promise< JMUserInfo | {} > { return; // We add return; here to avoid any IDE / Compiler errors } @Cordova() getUserInfo(params: { username: string; appKey?: string; }): Promise<JMUserInfo> { return; } @Cordova() updateMyPassword(params: { oldPwd: string; newPwd: string; }): Promise<void> { return; } /** * 更新当前用户头像。 * @param {object} params = { * imgPath: string // 本地图片绝对路径。 * } * 注意 Android 与 iOS 的文件路径是不同的: * - Android 类似:/storage/emulated/0/DCIM/Camera/IMG_20160526_130223.jpg * - iOS 类似:/var/mobile/Containers/Data/Application/7DC5CDFF-6581-4AD3-B165-B604EBAB1250/tmp/photo.jpg */ @Cordova() updateMyAvatar(params: { imgPath: string; }): Promise<any> { return; } @Cordova() updateMyInfo(params: { birthday?: number; gender?: 'male' | 'female' | 'unknown'; extras?: { [key: string]: string; }; }): Promise<any> { return; } @Cordova() updateGroupAvatar(params: { id: string; imgPath: string; }): Promise<any> { return; } @Cordova() downloadThumbGroupAvatar(params: { id: string; }): Promise<any> { return; } @Cordova() downloadOriginalGroupAvatar(params: { id: string; }): Promise<any> { return; } @Cordova() setConversationExtras(params: JMAllType & { extras: { [key: string]: string; }; }): Promise<any> { return; } @Cordova() sendTextMessage(params: JMAllType & JMMessageOptions & { text: string; }): Promise<any> { return; } @Cordova() sendImageMessage(params: JMAllType & JMMessageOptions & { path: string; }): Promise<any> { return; } @Cordova() sendVoiceMessage(params: JMAllType & JMMessageOptions & { path: string; }): Promise<any> { return; } @Cordova() sendCustomMessage(params: JMAllType & JMMessageOptions & { customObject: { [key: string]: string; }; }): Promise<any> { return; } @Cordova() sendLocationMessage(params: JMAllType & JMMessageOptions & { latitude: number; longitude: number; scale: number; address: string; }): Promise<any> { return; } @Cordova() sendFileMessage(params: JMAllType & JMMessageOptions & { path: string; }): Promise<any> { return; } @Cordova() retractMessage(params: JMAllType & { messageId: string; }): Promise<any> { return; } @Cordova() getHistoryMessages(params: (JMSingleType | JMGroupType) & { from: number; limit: number; }): Promise<any> { return; } @Cordova() getMessageById(params: JMAllType & { messageId: string; }): Promise<any> { return; } @Cordova() deleteMessageById(params: JMAllType & { messageId: string; }): Promise<any> { return; } @Cordova() sendInvitationRequest(params: { username: string; reason: string; appKey?: string; }): Promise<any> { return; } @Cordova() acceptInvitation(params: { username: string; appKey?: string; }): Promise<any> { return; } @Cordova() declineInvitation(params: { username: string; reason: string; appKey?: string; }): Promise<any> { return; } @Cordova() removeFromFriendList(params: { username: string; appKey?: string; }): Promise<any> { return; } @Cordova() updateFriendNoteName(params: { username: string; noteName: string; appKey?: string; }): Promise<any> { return; } @Cordova() updateFriendNoteText(params: { username: string; noteText: string; appKey?: string; }): Promise<any> { return; } @Cordova() getFriends(): Promise<any> { return; } @Cordova() createGroup(params: { groupType?: 'public' | 'private'; name?: string; desc?: string; }): Promise<string> { return; } @Cordova() getGroupIds(): Promise<any> { return; } @Cordova() getGroupInfo(params: { id: string; }): Promise<any> { return; } @Cordova() updateGroupInfo(params: { id: string; newName: string; newDesc?: string; } | { id: string; newDesc: string; }): Promise<any> { return; } @Cordova() addGroupMembers(params: { id: string; usernameArray: string[]; appKey?: string; }): Promise<any> { return; } @Cordova() removeGroupMembers(params: { id: string; usernameArray: string[]; appKey?: string; }): Promise<any> { return; } @Cordova() exitGroup(params: { id: string; }): Promise<any> { return; } @Cordova() getGroupMembers(params: { id: string; }): Promise<JMGroupMemberInfo[]> { return; } @Cordova() addUsersToBlacklist(params: { usernameArray: string[]; appKey?: string; }): Promise<any> { return; } @Cordova() removeUsersFromBlacklist(params: { usernameArray: string[]; appKey?: string; }): Promise<any> { return; } @Cordova() getBlacklist(): Promise<any> { return; } @Cordova() setNoDisturb(params: (JMSingleType | JMGroupType) & { isNoDisturb: boolean; }): Promise<any> { return; } @Cordova() getNoDisturbList(): Promise<any> { return; } @Cordova() setNoDisturbGlobal(params: { isNoDisturb: boolean; }): Promise<any> { return; } @Cordova() isNoDisturbGlobal(): Promise<any> { return; } @Cordova() blockGroupMessage(params: { id: string; isBlock: boolean; }): Promise<any> { return; } @Cordova() isGroupBlocked(params: { id: string; }): Promise<any> { return; } @Cordova() getBlockedGroupList(): Promise<any> { return; } @Cordova() downloadThumbUserAvatar(params: { username: string; appKey?: string; }): Promise<any> { return; } @Cordova() downloadOriginalUserAvatar(params: { username: string; appKey?: string; }): Promise<any> { return; } @Cordova() downloadThumbImage(params: (JMSingleType | JMGroupType) & { messageId: string; }): Promise<any> { return; } @Cordova() downloadOriginalImage(params: (JMSingleType | JMGroupType) & { messageId: string; }): Promise<any> { return; } @Cordova() downloadVoiceFile(params: (JMSingleType | JMGroupType) & { messageId: string; }): Promise<any> { return; } @Cordova() downloadFile(params: (JMSingleType | JMGroupType) & { messageId: string; }): Promise<any> { return; } @Cordova() createConversation(params: JMAllType): Promise<any> { return; } @Cordova() deleteConversation(params: JMAllType): Promise<any> { return; } @Cordova() enterConversation(params: JMSingleType | JMGroupType): Promise<any> { return; } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) exitConversation(params: JMSingleType | JMGroupType): void {} @Cordova() getConversation(params: JMAllType): Promise<any> { return; } @Cordova() getConversations(): Promise<any> { return; } @Cordova() resetUnreadMessageCount(params: JMAllType): Promise<any> { return; } @Cordova() transferGroupOwner(params: { groupId: string; username: string; appKey?: string; }): Promise<any> { return; } @Cordova() setGroupMemberSilence(params: { groupId: string; isSilence: boolean; username: string; appKey?: string; }): Promise<any> { return; } @Cordova() isSilenceMember(params: { groupId: string; username: string; appKey?: string; }): Promise<any> { return; } @Cordova() groupSilenceMembers(params: { groupId: string; }): Promise<any> { return; } @Cordova() setGroupNickname(params: { groupId: string; nickName: string; username: string; appKey?: string; }): Promise<any> { return; } /** * TODO: * * chatRoom internal api. */ @CordovaProperty() ChatRoom: JMChatRoom; @Cordova() enterChatRoom(params: { roomId: string; }): Promise<any> { return; } @Cordova() exitChatRoom(params: { roomId: string; }): Promise<any> { return; } @Cordova() getChatRoomConversation(params: { roomId: string; }): Promise<any> { return; } @Cordova() getChatRoomConversationList(): Promise<any> { return; } @Cordova() getAllUnreadCount(): Promise< { count: number; } > { return; // We add return; here to avoid any IDE / Compiler errors } @Cordova() addGroupAdmins(params: { groupId: string; usernames: string[]; appKey?: string; }): Promise<any> { return; } @Cordova() removeGroupAdmins(params: { groupId: string; usernames: string[]; appKey?: string; }): Promise<any> { return; } @Cordova() changeGroupType(params: { groupId: string; type: 'public' | 'private'; }): Promise<any> { return; } @Cordova() getPublicGroupInfos(params: { appKey: string; start: number; count: number; }): Promise<any> { return; } @Cordova() applyJoinGroup(params: { groupId: string; reason?: string; }): Promise<any> { return; } @Cordova() processApplyJoinGroup(params: { events: string[]; isAgree: boolean; isRespondInviter: boolean reason?: string; }): Promise<any> { return; } @Cordova() dissolveGroup(params: { groupId: string; }): Promise<any> { return; } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addReceiveMessageListener(params: JMMessageEventListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeReceiveMessageListener(params: JMMessageEventListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addClickMessageNotificationListener(params: JMMessageEventListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeClickMessageNotificationListener(params: JMMessageEventListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addSyncOfflineMessageListener(params: JMSyncOfflineMessageListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeSyncOfflineMessageListener(params: JMSyncOfflineMessageListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addSyncRoamingMessageListener(params: JMSyncRoamingMessageListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeSyncRoamingMessageListener(params: JMSyncRoamingMessageListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addLoginStateChangedListener(params: JMLoginStateChangedListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeLoginStateChangedListener(params: JMLoginStateChangedListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addContactNotifyListener(params: JMContactNotifyListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeContactNotifyListener(params: JMContactNotifyListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addMessageRetractListener(params: JMMessageRetractListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeMessageRetractListener(params: JMMessageRetractListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addReceiveTransCommandListener(params: JMReceiveTransCommandListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeReceiveTransCommandListener(params: JMReceiveTransCommandListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addReceiveChatRoomMessageListener(params: JMReceiveChatRoomMessageListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeReceiveChatRoomMessageListener(params: JMReceiveChatRoomMessageListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addReceiveApplyJoinGroupApprovalListener(params: JMReceiveApplyJoinGroupApprovalListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeReceiveApplyJoinGroupApprovalListener(params: JMReceiveApplyJoinGroupApprovalListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addReceiveGroupAdminRejectListener(params: JMReceiveGroupAdminRejectListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeReceiveGroupAdminRejectListener(params: JMReceiveGroupAdminRejectListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) addReceiveGroupAdminApprovalListener(params: JMReceiveGroupAdminApprovalListener): void { } @Cordova({ sync: true, platforms: ['iOS', 'Android'] }) removeReceiveGroupAdminApprovalListener(params: JMReceiveGroupAdminApprovalListener): void { } }
the_stack
import { IDisposableObject } from "./disposable"; export interface ITreeLeaf<ItemType> { name: string, item: ItemType | undefined, /** * Only null if is root leaf */ parent: ITreeLeaf<ItemType> | null, children: Record<string, ITreeLeaf<ItemType>>, } export type ITreeLeafTraverser<ItemType> = (leaf: ITreeLeaf<ItemType>, fullItemPath: string) => void | Promise<void>; export type ITreeOptionalItemTraverser<ItemType> = (item: ItemType | undefined, fullItemPath: string) => void | Promise<void>; export type ITreeItemTraverser<ItemType> = (item: ItemType | undefined, fullItemPath: string) => void | Promise<void>; export class Tree<ItemType> implements IDisposableObject { protected rootLeafs: Record<string, ITreeLeaf<ItemType>> = Object.create(null); protected pathsMap: Record<string, ItemType> = Object.create(null); protected reversePathsMap: Map<ItemType, string> = new Map(); constructor( public readonly rootPath: string, public readonly separator: string, ) {} dispose() { this.traverseAll(this.boundDeleteLeafItem); this.rootLeafs = Object.create(null); this.pathsMap = Object.create(null); this.reversePathsMap.clear(); } get(fullItemPath: string): ItemType | undefined { return this.pathsMap[fullItemPath]; } add(fullItemPath: string, item: ItemType) { const leaf = this.getOrCreateLeaf(fullItemPath); leaf.item = item; this.pathsMap[fullItemPath] = item; this.reversePathsMap.set(item, fullItemPath); } prune(fullItemPath: string) { const leaf = this.getLeaf(fullItemPath); if (!leaf) { return; } this.traverseLeaf(leaf, this.boundDeleteLeafItem, fullItemPath); if (leaf.parent) { delete leaf.parent.children[leaf.name]; } else { delete this.rootLeafs[leaf.name]; } } delete(fullItemPath: string) { const leaf = this.getLeaf(fullItemPath); if (!leaf) { return; } this.deleteLeafItem(leaf, fullItemPath); } deleteDeep(fullItemPath: string) { const leaf = this.getLeaf(fullItemPath); if (!leaf) { return; } this.traverseLeaf(leaf, this.boundDeleteLeafItem, fullItemPath); } relocate(fromFullItemPath: string, toFullItemPath: string): boolean { const fromLeaf = this.getLeaf(fromFullItemPath); if (!fromLeaf) { return false; } if (fromLeaf.parent) { delete fromLeaf.parent.children[fromLeaf.name]; } else { delete this.rootLeafs[fromLeaf.name]; } const toLeaf = this.getOrCreateLeaf(toFullItemPath); toLeaf.item = fromLeaf.item; toLeaf.children = fromLeaf.children; for (const childLeaf of Object.values(toLeaf.children)) { childLeaf.parent = toLeaf; } // Update paths for items in maps this.traverseLeaf(toLeaf, (leaf, fullLeafPath) => { if (!leaf.item) { return; } const oldFullLeafPath = this.reversePathsMap.get(leaf.item); if (!oldFullLeafPath) { return; } delete this.pathsMap[oldFullLeafPath]; this.pathsMap[fullLeafPath] = leaf.item; this.reversePathsMap.set(leaf.item, fullLeafPath); }, toFullItemPath); return true; } getAll(): ItemType[] { return Object.values(this.pathsMap); } traversePath(fullItemPath: string, fn: ITreeLeafTraverser<ItemType>) { const itemPath = this.getPath(fullItemPath); let currentItemName = itemPath.shift(); if (!currentItemName) { return; } let currentLeaf = this.rootLeafs[currentItemName]; let currentLeafPath = this.joinPath(this.rootPath, currentItemName); while (currentLeaf) { fn(currentLeaf, currentLeafPath); currentItemName = itemPath.shift(); if (!currentItemName) { return; } currentLeaf = currentLeaf.children[currentItemName]; currentLeafPath = this.joinPath(currentLeafPath, currentItemName); } } traverseAll(fn: ITreeLeafTraverser<ItemType>) { for (const [leafName, leafChild] of Object.entries(this.rootLeafs)) { this.traverseLeaf(leafChild, fn, this.joinPath(this.rootPath, leafName)); } } traverseLeaf(leaf: ITreeLeaf<ItemType>, fn: ITreeLeafTraverser<ItemType>, startPath: string) { for (const [leafName, leafChild] of Object.entries(leaf.children)) { this.traverseLeaf(leafChild, fn, this.joinPath(startPath, leafName)); } // Inside-out traversing fn(leaf, startPath); } traverseItemsWithin(fullItemPath: string, fn: ITreeItemTraverser<ItemType>) { return this.traverseOptionalItemsWithin(fullItemPath, (item, fullLeafPath) => item && fn(item, fullLeafPath)); } traverseOptionalItemsWithin(fullItemPath: string, fn: ITreeOptionalItemTraverser<ItemType>) { const leaf = this.getLeaf(fullItemPath); if (!leaf) { return; } this.traverseLeaf(leaf, (nestedLeaf, fullLeafPath) => fn(nestedLeaf.item, fullLeafPath), fullItemPath); } protected boundDeleteLeafItem = (leaf: ITreeLeaf<ItemType>, fullItemPath: string) => this.deleteLeafItem(leaf, fullItemPath); protected deleteLeafItem(leaf: ITreeLeaf<ItemType>, fullItemPath: string) { if (leaf.item) { delete this.pathsMap[fullItemPath]; this.reversePathsMap.delete(leaf.item) leaf.item = undefined; } } protected getLeaf(fullItemPath: string): ITreeLeaf<ItemType> | undefined { return this.getLeafByPath(this.getPath(fullItemPath)); } protected getParentLeaf(fullItemPath: string): ITreeLeaf<ItemType> | undefined { return this.getLeafByPath(this.getPathParentPath(this.getPath(fullItemPath))); } protected getLeafByPath([inRootName, ...itemPath]: string[]): ITreeLeaf<ItemType> | undefined { if (!inRootName) { return; } if (!itemPath.length) { return this.rootLeafs[inRootName]; } return itemPath.reduce((leaf, pathPart) => leaf?.children[pathPart], this.rootLeafs[inRootName]); } protected getOrCreateLeaf(fullItemPath: string): ITreeLeaf<ItemType> { const [inRootName, ...itemPath] = this.getPath(fullItemPath); if (!inRootName) { throw new Error(`Cannot create tree leaf for "${fullItemPath}" when root path is "${this.rootPath}"`); } const rootLeaf = this.rootLeafs[inRootName] ??= { name: inRootName, item: undefined, parent: null, children: {}, }; if (!itemPath.length) { return rootLeaf; } return itemPath.reduce((leaf, pathPart) => leaf.children[pathPart] ??= { name: pathPart, item: undefined, parent: leaf, children: {}, }, rootLeaf); } protected getPath(fullItemPath: string): string[] { return fullItemPath.substr(this.rootPath.length + this.separator.length).split(this.separator); } protected getPathName(itemPath: string[]): string { return itemPath[itemPath.length - 1]; } protected getPathParentPath(itemPath: string[]): string[] { return itemPath.slice(0, -1); } protected joinPath(root: string, leafName: string): string { return root + this.separator + leafName; } toJSON() { return { path: this.rootPath, pathsMap: Object.entries(this.pathsMap).reduce((json, [path, item]) => { json[path] = this.itemToJSON(item); return json; }, {}), children: Object.entries(this.rootLeafs).reduce((json, [name, leaf]) => { json[name] = this.leafToJSON(leaf, this.joinPath(this.rootPath, name)); return json; }, {} as any), }; } private leafToJSON(leaf: ITreeLeaf<ItemType>, fullLeafPath: string) { return { path: fullLeafPath, item: leaf.item ? this.itemToJSON(leaf.item) : undefined, children: Object.entries(leaf.children).reduce((children, [name, leaf]) => { children[name] = this.leafToJSON(leaf, this.joinPath(fullLeafPath, name)); return children; }, {} as Record<string, any>), }; } protected itemToJSON(item: ItemType): any { return 'item'; } } export class AsyncTree<ItemType> extends Tree<ItemType> { override async prune(fullItemPath: string): Promise<void> { const leaf = this.getLeaf(fullItemPath); if (!leaf) { return; } await this.traverseLeaf(leaf, this.boundDeleteLeafItem, fullItemPath); } override async delete(fullItemPath: string): Promise<void> { const leaf = this.getLeaf(fullItemPath); if (!leaf) { return; } return this.deleteLeafItem(leaf, fullItemPath); } override async deleteDeep(fullItemPath: string): Promise<void> { const leaf = this.getLeaf(fullItemPath); if (!leaf) { return; } return this.traverseLeaf(leaf, this.boundDeleteLeafItem, fullItemPath); } override async traversePath(fullItemPath: string, fn: ITreeLeafTraverser<ItemType>) { const itemPath = this.getPath(fullItemPath); let currentItemName = itemPath.shift(); if (!currentItemName) { return; } let currentLeaf = this.rootLeafs[currentItemName]; let currentLeafPath = this.joinPath(this.rootPath, currentItemName); while (currentLeaf) { await fn(currentLeaf, currentLeafPath); currentItemName = itemPath.shift(); if (!currentItemName) { return; } currentLeaf = currentLeaf.children[currentItemName]; currentLeafPath = this.joinPath(currentLeafPath, currentItemName); } } override async traverseLeaf(leaf: ITreeLeaf<ItemType>, fn: ITreeLeafTraverser<ItemType>, startPath: string): Promise<void> { await Promise.all(Object.entries(leaf.children).map(([leafName, leafChild]) => { return this.traverseLeaf(leafChild, fn, this.joinPath(startPath, leafName)); })); // Inside-out traverse await fn(leaf, startPath); } override traverseItemsWithin(fullItemPath: string, fn: ITreeItemTraverser<ItemType>): Promise<void> { return this.traverseOptionalItemsWithin(fullItemPath, (item, fullLeafPath) => item && fn(item, fullLeafPath)); } override async traverseOptionalItemsWithin(fullItemPath: string, fn: ITreeOptionalItemTraverser<ItemType>): Promise<void> { const leaf = this.getLeaf(fullItemPath); if (!leaf) { return; } await this.traverseLeaf(leaf, (nestedLeaf, fullLeafPath) => fn(nestedLeaf.item, fullLeafPath), fullItemPath); } override async traverseAll(fn: ITreeLeafTraverser<ItemType>): Promise<void> { for (const [leafName, leafChild] of Object.entries(this.rootLeafs)) { await this.traverseLeaf(leafChild, fn, this.joinPath(this.rootPath, leafName)); } } }
the_stack
import { childProcess, createTmpDir, injectReactNativeVersionKeysInObject, iosUtil, kax, log, manifest, mustacheUtils, NativePlatform, PackagePath, PluginConfig, readPackageJson, shell, utils, writePackageJson, yarn, config as ernConfig, } from 'ern-core'; import { ContainerGenerator, ContainerGeneratorConfig, ContainerGenResult, generateContainer, generatePluginsMustacheViews, populateApiImplMustacheView, } from 'ern-container-gen'; import fs from 'fs-extra'; import path from 'path'; import xcode from 'xcode-ern'; import _ from 'lodash'; import readDir from 'fs-readdir-recursive'; import { Composite } from 'ern-composite-gen'; import semver from 'semver'; const ROOT_DIR = process.cwd(); const PATH_TO_TEMPLATES_DIR = path.join(__dirname, 'templates'); const PATH_TO_HULL_DIR = path.join(__dirname, 'hull'); export default class IosGenerator implements ContainerGenerator { get name(): string { return 'IosGenerator'; } get platform(): NativePlatform { return 'ios'; } public async generate( config: ContainerGeneratorConfig, ): Promise<ContainerGenResult> { return generateContainer(config, { fillContainerHull: this.fillContainerHull.bind(this), postCopyRnpmAssets: this.addResources.bind(this), }); } public async addResources(config: ContainerGeneratorConfig) { const containerProjectPath = path.join( config.outDir, 'ElectrodeContainer.xcodeproj', 'project.pbxproj', ); const containerIosProject = await this.getIosContainerProject( containerProjectPath, ); const containerResourcesPath = path.join( config.outDir, 'ElectrodeContainer', 'Resources', ); // Get all resources files from the 'Resources' directory // Some processing is done here to properly handle `.xcassets` // files which are directories containing assets. // But we don't want to add independent files from this directory // to the pbxproj, but only the top level `.xcassets` directory. // // For example, an `xcassets` directory might look like this // // Media.xcassets // ├── Contents.json // ├── Face-ID.imageset // │   ├── Contents.json // │   └── faceid.pdf // ├── IconUser.imageset // │   ├── Contents.json // │   └── IconUser.pdf // // Which will result in recursive readir call returning the // following paths // // Media.xcassets/Contents.json // Media.xcassets/Face-ID.imageset/Contents.json // Media.xcassets/Face-ID.imageset/faceid.pdf // ... // // Each of these individual files would then wrongly be // added to the pbxproj as resources. // However we just want top level directory Media.xcassets // to be added to the pbxproj, thus the special processing. const resourceFiles = _.uniq( readDir(containerResourcesPath).map((f) => f.replace(/(\.xcassets)(\/.+)$/, '$1'), ), ); resourceFiles.forEach((resourceFile) => { containerIosProject.addResourceFile( path.join('Resources', resourceFile), null, containerIosProject.findPBXGroupKey({ name: 'Resources' }), ); }); fs.writeFileSync(containerProjectPath, containerIosProject.writeSync()); } public async fillContainerHull( config: ContainerGeneratorConfig, ): Promise<void> { if (process.platform !== 'darwin' && !config?.iosConfig?.skipInstall) { throw new Error( `Full iOS Container generation with pod installation is only supported on macOS. You can set 'iosConfig.skipInstall' in container generator config to skip the installation step. Or set --skipInstall if using the create-container command.`, ); } if (config?.iosConfig?.skipInstall) { log.info( `skipInstall option is set. 'yarn install' and 'pod install' won't be run after container generation. Make sure to run these commands before building the container.`, ); } const pathSpec = { outputDir: config.outDir, projectHullDir: path.join(PATH_TO_HULL_DIR, '{.*,*}'), rootDir: ROOT_DIR, }; const reactNativePlugin = _.find( config.plugins, (p) => p.name === 'react-native', ); if (!reactNativePlugin) { throw new Error('react-native was not found in plugins list !'); } if (!reactNativePlugin.version) { throw new Error('react-native plugin does not have a version !'); } const mustacheView: any = {}; mustacheView.jsMainModuleName = config.jsMainModuleName || 'index'; mustacheView.iosDeploymentTarget = config.iosConfig?.deploymentTarget ?? iosUtil.getDefaultIosDeploymentTarget(reactNativePlugin.version); injectReactNativeVersionKeysInObject( mustacheView, reactNativePlugin.version, ); const projectSpec = { deploymentTarget: mustacheView.iosDeploymentTarget, projectName: 'ElectrodeContainer', }; await kax .task('Preparing Native Dependencies Injection') .run(this.buildiOSPluginsViews(config.plugins, mustacheView)); await kax .task('Preparing API Implementations Injection') .run( this.buildApiImplPluginViews( config.plugins, config.composite, mustacheView, projectSpec, ), ); if (semver.gte(reactNativePlugin.version!, '0.61.0')) { shell.pushd(config.outDir); try { await yarn.init(); // Add @react-native-community/cli-platform-ios because // it contains the scripts needed for native modules pods linking // look in composite to match proper version const compositeNodeModulesPath = path.join( config.composite.path, 'node_modules', ); const cliPlatformIosPkg = '@react-native-community/cli-platform-ios'; const cliPlatformIosPkgVersion = ( await readPackageJson( path.join(compositeNodeModulesPath, cliPlatformIosPkg), ) ).version; await yarn.add( PackagePath.fromString( `${cliPlatformIosPkg}@${cliPlatformIosPkgVersion}`, ), ); await yarn.add( PackagePath.fromString(`react-native@${reactNativePlugin.version}`), ); // // Add all native dependencies to package.json dependencies so that // !use_native_modules can detect them to add their pod to the Podfile const dependencies = await config.composite.getNativeDependencies({}); const resDependencies = [ ...dependencies.thirdPartyInManifest, ...dependencies.thirdPartyNotInManifest, ]; const addDependencies: any = {}; resDependencies.forEach((p) => { addDependencies[p.name!] = p.version; }); // // Create package.json in container directory root // so that native modules pods can be resolved // by use_native_modules! RN ruby script const pjsonObj = { dependencies: addDependencies, name: 'container', private: true, }; await writePackageJson(config.outDir, pjsonObj); // // Copy all native dependencies from composite node_modules // to container node_modules so that pods can be found local // to the container directory // [only for full iOS container generation] if (!config?.iosConfig?.skipInstall) { const containerNodeModulesPath = path.join( config.outDir, 'node_modules', ); shell.mkdir('-p', containerNodeModulesPath); resDependencies.forEach((p) => { const depPath = p.basePath!.match(/node_modules\/(.+)/)![1]; const targetPath = path.join(containerNodeModulesPath, depPath); shell.mkdir('-p', targetPath); shell.cp('-rf', path.join(p.basePath!, '{.*,*}'), targetPath); }); } else { shell.rm('-rf', 'node_modules'); } } finally { shell.popd(); } } const { iosProject, projectPath } = await iosUtil.fillProjectHull( pathSpec, projectSpec, config.plugins, mustacheView, config.composite, config.iosConfig, ); await kax .task('Adding MiniAppNavigationController Classes') .run(this.addMiniAppNavigationControllerClasses(config, iosProject)); await kax .task('Adding Native Dependencies Hooks') .run( this.addiOSPluginHookClasses(iosProject, config.plugins, config.outDir), ); fs.writeFileSync(projectPath, iosProject.writeSync()); if (semver.gte(reactNativePlugin.version!, '0.61.0')) { // For full iOS container generation, run 'pod install' // and also add all essential node_modules (needed for the build) // to the container if (!config?.iosConfig?.skipInstall) { const podVersionArg = ernConfig.get('podVersion') ? `_${ernConfig.get('podVersion')}_` : ''; const podCmdArgs = [podVersionArg, 'install', '--verbose'].filter( (x: string) => x !== '', ); shell.pushd(config.outDir); try { await kax .task(`Running pod ${podCmdArgs.join(' ')}`) .run(childProcess.spawnp('pod', podCmdArgs)); } finally { shell.popd(); } // // Clean node_modules by only keeping the directories that are // needed for proper container build. shell.pushd(config.outDir); try { // // Look in the Pods pbxproj for any references to some files // kepts in some node_module subdirectory (basically react-native // as well as all native modules) const f = fs.readFileSync('Pods/Pods.xcodeproj/project.pbxproj', { encoding: 'utf8', }); // // Build an array of these directories const re = RegExp('"?../node_modules/([^"]+)"?;', 'g'); const matches = []; let match = re.exec(f); while (match !== null) { matches.push(match[1]); match = re.exec(f); } const res = matches .map((r) => r.split('/')) .filter((x) => x[0] !== 'react-native') .map((x) => x.join('/')) .concat('react-native'); // // Copy all retained directories from 'node_modules' // to a new directory 'node_modules_light' const nodeModulesLightDir = 'node_modules_light'; const nodeModulesDir = 'node_modules'; shell.mkdir('-p', nodeModulesLightDir); for (const b of res) { shell.mkdir('-p', path.join(nodeModulesLightDir, b)); shell.cp( '-Rf', path.join(nodeModulesDir, b, '{.*,*}'), path.join(nodeModulesLightDir, b), ); } // // Replace the huge 'node_modules' directory with the skimmed one shell.rm('-rf', nodeModulesDir); shell.mv(nodeModulesLightDir, nodeModulesDir); // // Finally get rid of all android directories to further reduce // overall 'node_modules' directory size, as they are not needed // for iOS container builds. shell.rm('-rf', path.join(nodeModulesDir, '**/android')); if (semver.gte(reactNativePlugin.version!, '0.64.0')) { // Starting with React Native 0.64.0, code generation for Turbo Modules // is performed using react-native-codegen package. // The package entry point is invoked during Xcode build of FBReactNativeSpec // iOS project (run as a build phase script). // It therefore needs to be present in the node modules of the Container. // // TODO : Dig deeper to figure out if we could instead call this script during // container generation and get rid of the the build script phase after doing // that, so that we don't clutter node_modules of the container pushed to git // and that Node does not have to be a requirement to build containers. await this.addReactNativeCodeGen(config.outDir); } } finally { shell.popd(); } } } } public async addReactNativeCodeGen(targetDir: string): Promise<void> { log.debug('Adding react-native-codegen package'); const tmpDir = createTmpDir(); shell.pushd(tmpDir); try { await yarn.init(); await yarn.add(PackagePath.fromString('react-native-codegen')); // mkdirp and invariant are also needed await yarn.add(PackagePath.fromString('mkdirp')); await yarn.add(PackagePath.fromString('invariant')); shell.rm('-rf', [ 'package.json', 'yarn.lock', 'node_modules/.yarn-integrity', ]); shell.cp('-Rf', path.join(tmpDir, 'node_modules'), targetDir); } finally { shell.popd(); } } // Code to keep backward compatibility public switchToOldDirectoryStructure( pluginSourcePath: string, tail: string, ): boolean { // This is to check if the api referenced during container generation is created using the old or new directory structure to help keep the backward compatibility. const pathToSwaggersAPIs = path.join( 'IOS', 'IOS', 'Classes', 'SwaggersAPIs', ); if ( path.dirname(tail) === 'IOS' && fs.pathExistsSync( path.join(pluginSourcePath, path.dirname(pathToSwaggersAPIs)), ) ) { return true; } return false; } public async buildiOSPluginsViews( plugins: PackagePath[], mustacheView: any, ): Promise<any> { mustacheView.plugins = await generatePluginsMustacheViews(plugins, 'ios'); } public async addiOSPluginHookClasses( containerIosProject: any, plugins: PackagePath[], outDir: string, ): Promise<any> { for (const plugin of plugins) { if (plugin.name === 'react-native') { continue; } const pluginConfig: PluginConfig<'ios'> | undefined = await manifest.getPluginConfig(plugin, 'ios'); if (!pluginConfig) { log.warn( `${plugin.name} does not have any injection configuration for ios platform`, ); continue; } const { pluginHook } = pluginConfig!; if (pluginHook?.name) { if (!pluginConfig.path) { throw new Error('No plugin config path was set. Cannot proceed.'); } const pluginConfigPath = pluginConfig.path; const pathToCopyPluginHooksTo = path.join(outDir, 'ElectrodeContainer'); log.debug(`Adding ${pluginHook.name}.h`); const pathToPluginHookHeader = path.join( pluginConfigPath, `${pluginHook.name}.h`, ); shell.cp(pathToPluginHookHeader, pathToCopyPluginHooksTo); containerIosProject.addHeaderFile( `${pluginHook.name}.h`, { public: true }, containerIosProject.findPBXGroupKey({ name: 'ElectrodeContainer' }), ); log.debug(`Adding ${pluginHook.name}.m`); const pathToPluginHookSource = path.join( pluginConfigPath, `${pluginHook.name}.m`, ); shell.cp(pathToPluginHookSource, pathToCopyPluginHooksTo); containerIosProject.addSourceFile( `${pluginHook.name}.m`, null, containerIosProject.findPBXGroupKey({ name: 'ElectrodeContainer' }), ); } } } public async getIosContainerProject( containerProjectPath: string, ): Promise<any> { const containerProject = xcode.project(containerProjectPath); return new Promise((resolve, reject) => { containerProject.parse((err: any) => { if (err) { reject(err); } resolve(containerProject); }); }); } public async buildApiImplPluginViews( plugins: PackagePath[], composite: Composite, mustacheView: any, projectSpec: any, ) { for (const plugin of plugins) { const pluginConfig = await manifest.getPluginConfig( plugin, 'ios', projectSpec.projectName, ); if (!pluginConfig) { continue; } if (await utils.isDependencyPathNativeApiImpl(plugin.basePath)) { populateApiImplMustacheView(plugin.basePath, mustacheView, true); } } if (mustacheView.apiImplementations) { mustacheView.hasApiImpl = true; for (const api of mustacheView.apiImplementations) { if (api.hasConfig) { mustacheView.hasAtleastOneApiImplConfig = true; break; } } } } public async addMiniAppNavigationControllerClasses( config: ContainerGeneratorConfig, containerIosProject: any, ) { const partialProxy = (name: string) => { return fs.readFileSync( path.join(PATH_TO_TEMPLATES_DIR, `${name}.mustache`), 'utf8', ); }; log.debug('Creating miniapps config'); const configFileName = `MiniAppsConfig.swift`; const pathToMiniAppsConfigMustacheTemplate = path.join( PATH_TO_TEMPLATES_DIR, 'MiniAppsConfig.mustache', ); const pathToOutputConfigFile = path.join( config.outDir, 'ElectrodeContainer', 'MiniAppNavigationControllers', configFileName, ); const mustacheView: any = {}; mustacheView.miniApps = await config.composite.getMiniApps(); await mustacheUtils.mustacheRenderToOutputFileUsingTemplateFile( pathToMiniAppsConfigMustacheTemplate, mustacheView, pathToOutputConfigFile, partialProxy, ); const relativePathToConfigFile = path.join( 'MiniAppNavigationControllers', configFileName, ); containerIosProject.addFile( relativePathToConfigFile, containerIosProject.findPBXGroupKey({ name: 'MiniAppNavigationControllers', }), ); containerIosProject.addSourceFile( relativePathToConfigFile, null, containerIosProject.findPBXGroupKey({ name: 'MiniAppNavigationControllers', }), ); log.debug('Creating miniapp nav controllers'); const compositeMiniApps = await config.composite.getMiniApps(); for (const miniApp of compositeMiniApps) { const navControllerFileName = `${miniApp.pascalCaseName}NavigationController.swift`; log.debug(`Creating ${navControllerFileName}`); const pathToMiniAppNavControllerMustacheTemplate = path.join( PATH_TO_TEMPLATES_DIR, 'MiniAppNavigationController.mustache', ); const pathToOutputNavControllerFile = path.join( config.outDir, 'ElectrodeContainer', 'MiniAppNavigationControllers', navControllerFileName, ); await mustacheUtils.mustacheRenderToOutputFileUsingTemplateFile( pathToMiniAppNavControllerMustacheTemplate, miniApp, pathToOutputNavControllerFile, partialProxy, ); const relativePathToNavControllerFile = path.join( 'MiniAppNavigationControllers', navControllerFileName, ); containerIosProject.addFile( relativePathToNavControllerFile, containerIosProject.findPBXGroupKey({ name: 'MiniAppNavigationControllers', }), ); containerIosProject.addSourceFile( relativePathToNavControllerFile, null, containerIosProject.findPBXGroupKey({ name: 'MiniAppNavigationControllers', }), ); } } }
the_stack
import {Component, RefObject} from 'react'; import classNames from 'classnames'; import {ObjectVector2} from '../util/scenarioUtils'; function positionFromMouseEvent(event: React.MouseEvent<HTMLElement>, offsetX: number, offsetY: number): ObjectVector2 { const rect = event.currentTarget.getBoundingClientRect(); return { x: event.pageX + event.currentTarget.scrollLeft - rect.left - offsetX, y: event.pageY + event.currentTarget.scrollTop - rect.top - offsetY }; } function positionsFromTouchEvents(event: React.TouchEvent<HTMLElement>): ObjectVector2[] { const rect = event.currentTarget.getBoundingClientRect(); let result = []; for (let index = 0; index < event.touches.length; ++index) { result[index] = {x: event.touches[index].pageX - rect.left, y: event.touches[index].pageY - rect.top} } return result; } function vectorDifference(vec1: ObjectVector2, vec2: ObjectVector2): ObjectVector2 { return {x: vec1.x - vec2.x, y: vec1.y - vec2.y}; } function vectorMagnitude2(vec: ObjectVector2): number { return vec.x * vec.x + vec.y * vec.y; } function vectorMagnitude(vec: ObjectVector2): number { return Math.sqrt(vectorMagnitude2(vec)); } /** * Compare two vectors and determine if they're within 45 degrees to being parallel or antiparallel. * * @param vec1 The first vector to compare * @param vec2 The second vector to compare * @return (number) 1 or -1 if the two vectors are within 45 degrees of parallel or antiparallel, or 0 otherwise. */ export function sameOppositeQuadrant(vec1: ObjectVector2, vec2: ObjectVector2) { let dot = vec1.x * vec2.x + vec1.y * vec2.y; // Dot product is |vec1|*|vec2|*cos(theta). If we square it, we can divide by the magnitude squared of the two // vectors to end up with cos squared, which avoids having to square root the two vector magnitudes. let vec1Magnitude2 = vectorMagnitude2(vec1); let vec2Magnitude2 = vectorMagnitude2(vec2); let cos2 = dot * dot / (vec1Magnitude2 * vec2Magnitude2); // cos(45 degrees) is 1/sqrt(2), so cos^2(45 degrees) is 1/2. Also, squares are always positive (i.e. // cos^2(135) is also +1/2, and cos^2(180) is +1), so can just check if cos2 is > 0.5 return cos2 > 0.5 ? (dot > 0 ? 1 : -1) : 0; } type DragEventHandler = (delta: ObjectVector2, position: ObjectVector2, startPos: ObjectVector2) => void; export interface GestureControlsProps { moveThreshold: number; // pixels to move before cancelling tap/press pressDelay: number; // ms to wait before detecting a press preventDefault: boolean; // whether to preventDefault on all events stopPropagation: boolean; // whether to stopPropagation on all events onGestureStart?: (startPos: ObjectVector2) => void; onGestureEnd?: () => void; onTap?: (position: ObjectVector2) => void; onPress?: (position: ObjectVector2) => void; onPan?: DragEventHandler; onZoom?: DragEventHandler; onRotate?: DragEventHandler; className?: string; offsetX: number; // Adjustment in pixels to make to x coordinates, due to padding/margins around the element to handle gestures offsetY: number; // Adjustment in pixels to make to y coordinates, due to padding/margins around the element to handle gestures forwardRef?: RefObject<HTMLDivElement>; } export enum GestureControlsAction { NOTHING, TAPPING, PRESSING, PANNING, ZOOMING, ROTATING, TWO_FINGERS // can be either ZOOMING or ROTATING } export interface GestureControlsState { action: GestureControlsAction; lastPos?: ObjectVector2; startPos?: ObjectVector2; lastTouches?: ObjectVector2[]; } export const PAN_BUTTON = 0; export const ZOOM_BUTTON = 1; export const ROTATE_BUTTON = 2; export default class GestureControls extends Component<GestureControlsProps, GestureControlsState> { static defaultProps = { moveThreshold: 5, pressDelay: 1000, preventDefault: true, stopPropagation: true, offsetX: 0, offsetY: 0 }; private pressTimer: number | undefined; constructor(props: GestureControlsProps) { super(props); this.onMouseDown = this.onMouseDown.bind(this); this.onWheel = this.onWheel.bind(this); this.onContextMenu = this.onContextMenu.bind(this); this.onMouseMove = this.onMouseMove.bind(this); this.onMouseUp = this.onMouseUp.bind(this); this.onTouchStart = this.onTouchStart.bind(this); this.onTouchMove = this.onTouchMove.bind(this); this.onTouchEnd = this.onTouchEnd.bind(this); this.onPressTimeout = this.onPressTimeout.bind(this); this.state = { action: GestureControlsAction.NOTHING, lastPos: undefined, startPos: undefined }; } eventPrevent(event: React.MouseEvent<HTMLElement> | React.WheelEvent<HTMLElement> | React.TouchEvent<HTMLElement>) { if (this.props.preventDefault) { event.preventDefault(); } if (this.props.stopPropagation) { event.stopPropagation(); } } onMouseDown(event: React.MouseEvent<HTMLElement>) { if (event.isDefaultPrevented()) { // This is a hack, but stopping propagation doesn't work between the pingsComponent and here. return; } this.eventPrevent(event); const startPos = positionFromMouseEvent(event, this.props.offsetX, this.props.offsetY); switch (event.button) { case PAN_BUTTON: if (event.shiftKey) { // Holding down shift makes the PAN_BUTTON act like the ZOOM_BUTTON. this.setState({ action: GestureControlsAction.ZOOMING, lastPos: startPos, startPos }); } else if (event.ctrlKey) { // Holding down control makes it act like the ROTATE_BUTTON. this.setState({ action: GestureControlsAction.ROTATING, lastPos: startPos, startPos }); } else { this.setState({ action: GestureControlsAction.TAPPING, lastPos: startPos, startPos }); this.pressTimer = window.setTimeout(this.onPressTimeout, this.props.pressDelay); } break; case ZOOM_BUTTON: this.setState({ action: GestureControlsAction.ZOOMING, lastPos: startPos, startPos }); break; case ROTATE_BUTTON: this.setState({ action: GestureControlsAction.ROTATING, lastPos: startPos, startPos }); break; default: return; } this.props.onGestureStart && this.props.onGestureStart(startPos); } onPressTimeout() { // Held a press for the delay period - change state to PRESSING and emit onPress action this.setState({action: GestureControlsAction.PRESSING}); this.props.onPress && this.props.onPress(this.state.lastPos || this.state.startPos!); } onWheel(event: React.WheelEvent<HTMLElement>) { // deltaMode is 0 (pixels), 1 (lines) or 2 (pages). Scale up deltaY so they're roughly equivalent. const distance = event.deltaY * [0.07, 1, 7][event.deltaMode]; this.props.onZoom && this.props.onZoom({x: 0, y: distance}, {x: 0, y: 0}, {x: 0, y: 0}); } onContextMenu(event: React.MouseEvent<HTMLElement>) { this.eventPrevent(event); } dragAction(currentPos: ObjectVector2, callback?: DragEventHandler) { this.setState((prevState) => { const delta = vectorDifference(currentPos, prevState.lastPos!); callback && callback(delta, currentPos, prevState.startPos!); return {lastPos: currentPos}; }); } onMove(currentPos: ObjectVector2, action: GestureControlsAction) { switch (action) { case GestureControlsAction.TAPPING: case GestureControlsAction.PRESSING: if (vectorMagnitude2(vectorDifference(currentPos, this.state.lastPos!)) >= this.props.moveThreshold * this.props.moveThreshold) { window.clearTimeout(this.pressTimer); this.setState({ action: GestureControlsAction.PANNING }); this.dragAction(currentPos, this.props.onPan); } break; case GestureControlsAction.PANNING: return this.dragAction(currentPos, this.props.onPan); case GestureControlsAction.ZOOMING: return this.dragAction(currentPos, this.props.onZoom); case GestureControlsAction.ROTATING: return this.dragAction(currentPos, this.props.onRotate); default: } } onMouseMove(event: React.MouseEvent<HTMLElement>) { if (this.state.action !== GestureControlsAction.NOTHING) { this.eventPrevent(event); this.onMove(positionFromMouseEvent(event, this.props.offsetX, this.props.offsetY), this.state.action); } } onMouseUp(event: React.MouseEvent<HTMLElement>) { this.eventPrevent(event); this.onTapReleased(); } onTapReleased() { window.clearTimeout(this.pressTimer); this.props.onGestureEnd && this.props.onGestureEnd(); if (this.state.action === GestureControlsAction.TAPPING && this.props.onTap) { this.props.onTap(this.state.lastPos!); } this.setState({action: GestureControlsAction.NOTHING, lastPos: undefined, startPos: undefined}); } onTouchChange(event: React.TouchEvent<HTMLElement>, touchStarted: boolean) { // this.eventPrevent(event); switch (event.touches.length) { case 0: return this.onTapReleased(); case 1: // Single finger touch is the same as tapping/pressing/panning with LMB. const startPos = positionsFromTouchEvents(event)[0]; if (touchStarted && this.props.onGestureStart) { this.props.onGestureStart(startPos); } // If touchStarted is false (went from > 1 finger down to 1 finger), go straight to PANNING this.setState({ action: touchStarted ? GestureControlsAction.TAPPING : GestureControlsAction.PANNING, lastPos: startPos, startPos }); // If touchStarted is true, they just touched with one finger - might be the start of a press. if (touchStarted) { this.pressTimer = window.setTimeout(this.onPressTimeout, this.props.pressDelay); } break; case 2: // Two finger touch can pinch to zoom or drag to rotate. window.clearTimeout(this.pressTimer); const lastTouches = positionsFromTouchEvents(event); this.setState({ action: GestureControlsAction.TWO_FINGERS, lastTouches, startPos: this.state.startPos || lastTouches[0] }); break; default: // Three or more fingers - do nothing until we're back to a handled number window.clearTimeout(this.pressTimer); this.setState({ action: GestureControlsAction.NOTHING }); break; } } onTouchStart(event: React.TouchEvent<HTMLElement>) { this.onTouchChange(event, true); } onTouchEnd(event: React.TouchEvent<HTMLElement>) { this.onTouchChange(event, false); } touchDragAction(currentPos: ObjectVector2[], callback: DragEventHandler | undefined, value: ObjectVector2) { this.setState(() => { callback && callback(value, currentPos[0], this.state.startPos!); return {lastTouches: currentPos}; }); } onTouchMove(event: React.TouchEvent<HTMLElement>) { // this.eventPrevent(event); if (this.state.action !== GestureControlsAction.NOTHING) { const currentPos = positionsFromTouchEvents(event); switch (currentPos.length) { case 1: return this.onMove(currentPos[0], this.state.action); case 2: // with two-finger gesture, can switch between zooming and rotating const delta = this.state.lastTouches!.map((lastPos, index) => (vectorDifference(currentPos[index], lastPos))); const largerIndex = (vectorMagnitude2(delta[0]) > vectorMagnitude2(delta[1])) ? 0 : 1; const smallerIndex = 1 - largerIndex; let deltaParallel = sameOppositeQuadrant(delta[0], delta[1]); if (deltaParallel > 0) { // fingers moving in the same direction - user is rotating vertically this.touchDragAction(currentPos, this.props.onRotate, {x: 0, y: delta[largerIndex].y}); } else { let deltaFingers = vectorDifference(currentPos[largerIndex], currentPos[smallerIndex]); let fingerNormal = {x: deltaFingers.y, y: -deltaFingers.x}; let dotFinger = sameOppositeQuadrant(delta[largerIndex], fingerNormal); if (dotFinger === 0) { // not moving clockwise/anticlockwise - zoom const lastBetween = vectorMagnitude(vectorDifference(this.state.lastTouches![1], this.state.lastTouches![0])); const between = vectorMagnitude(vectorDifference(currentPos[1], currentPos[0])); this.touchDragAction(currentPos, this.props.onZoom, { x: 0, y: lastBetween - between }); } else { // moving clockwise/anticlockwise - rotating in XZ plane let magnitude = vectorMagnitude(delta[largerIndex]); this.touchDragAction(currentPos, this.props.onRotate, {x: dotFinger * magnitude, y: 0}); } } break; default: } } } render() { return ( <div className={classNames('gestureControls', this.props.className)} onMouseDown={this.onMouseDown} onWheel={this.onWheel} onContextMenu={this.onContextMenu} onMouseMove={this.onMouseMove} onMouseUp={this.onMouseUp} onTouchStart={this.onTouchStart} onTouchMove={this.onTouchMove} onTouchEnd={this.onTouchEnd} ref={this.props.forwardRef} > {this.props.children} </div> ); } }
the_stack
import * as React from 'react'; import styled from '../../utils/styled'; import { StandardProps } from '../../common'; import { InteractiveSurface, InteractiveSurfaceChangeEvent } from '../InteractiveSurface'; import { Grid, GridLayout } from '../Grid'; import { GridArea, GridAreaTapEvent } from '../GridArea'; export interface DashboardTile { /** * Id of the tile, must be unique. */ id: string; /** * The column placement for the tile. By default auto. * @default auto */ column?: number; /** * The row placement for the tile. By default auto. * @default auto */ row?: number; /** * The number of columns spanned by the tile. By default 1. * @default 1 */ colSpan?: number; /** * The number of rows spanned by the tile. By default 1. * @default 1 */ rowSpan?: number; /** * Determines whether the tile is hidden or not. * @default false */ hidden?: boolean; } export interface DashboardChangeEvent { /** * The tile that originated the change. */ tile: DashboardTile; /** * The reconstructed dashboard layout. */ tiles: Array<DashboardTile>; } export interface DashboardProps extends StandardProps { /** * The number of rows in the dashboard grid. By default flexible. * @default auto */ rowCount?: number; /** * The height per row in pixel. By default auto. * @default auto */ rowHeight?: number; /** * The number of columns in the dashboard grid. By default 5. * @default 5 */ columnCount?: number; /** * The height per row in pixel. By default auto. * @default auto */ columnWidth?: number; /** * The spacing between the grid cells in pixel. By default 10. * @default 10 */ spacing?: number; /** * The default tile arrangement to use. Only managed mode exist. Setting * this property later will reset the tile layout to the given one. */ defaultTiles: Array<DashboardTile>; /** * Fired when the dashboard layout is changed. */ onChange?(e: DashboardChangeEvent): void; /** * Disables the ability to change the layout. By default false. * @default false */ disabled?: boolean; /** * Enables the live preview during the tile drag with a standard * or custom element. */ preview?: React.ReactChild | boolean; /** * By providing the show tile property, the dashboard will render * the unused tiles. */ emptyTiles?: boolean; /** * The content to consider for the dashboard. */ children?: React.ReactNode; /** * Gets the reference to the underlying HTML DOM element. */ innerRef?(instance: HTMLElement | null): void; } export interface DashboardState { tiles: Array<DashboardTile>; live?: Array<DashboardTile>; } function clamp(lower: number, value: number, upper: number) { return Math.min(Math.max(lower, value), upper); } function calc(rel: number, off: number, total: number, dim: number) { const value = clamp(0, rel * total - off, total - dim); return `${value}px`; } function repeat(count: number | undefined, dim?: number) { const value = dim !== undefined ? `${dim}px` : '1fr'; if (count !== undefined) { const values: Array<string> = []; for (let i = 0; i < count; i++) { values.push(value); } return values; } return value; } function collides(a: DashboardTile, b: DashboardTile) { if (a.hidden || b.hidden) { return false; } else if (a.column !== undefined && a.row !== undefined && b.column !== undefined && b.row !== undefined) { const { colSpan: acp = 1, rowSpan: arp = 1 } = a; const { colSpan: bcp = 1, rowSpan: brp = 1 } = b; const acs = a.column; const ace = a.column + acp - 1; const ars = a.row; const are = a.row + arp - 1; const bcs = b.column; const bce = b.column + bcp - 1; const brs = b.row; const bre = b.row + brp - 1; return acs <= bce && ace >= bcs && ars <= bre && are >= brs; } return false; } function notEqual(a: Array<DashboardTile>, b: Array<DashboardTile>) { if (a !== b) { if (a.length !== b.length) { return true; } for (let i = a.length; i--; ) { const at = a[i]; const bt = b[i]; if ( at !== bt || at.colSpan !== bt.colSpan || at.column !== bt.column || at.id !== bt.id || at.row !== bt.row || at.rowSpan !== bt.rowSpan ) { return true; } } } return false; } function resetStyle(node: HTMLElement) { const defaultValue = ''; const style = node.style; style.position = 'static'; style.cursor = defaultValue; style.width = defaultValue; style.height = defaultValue; style.left = defaultValue; style.top = defaultValue; style.zIndex = defaultValue; } const Preview = styled.div` background: #eee; border: 1px dashed #ccc; width: 100%; height: 100%; `; function getPreview(preview: React.ReactChild | boolean, tile: DashboardTile) { const content = preview === true ? <Preview /> : preview; return ( <GridArea colSpan={tile.colSpan} rowSpan={tile.rowSpan} column={tile.column} row={tile.row}> {content} </GridArea> ); } const defaultActiveTile = { x: 0, y: 0, width: 0, height: 0, }; function changeTile(oldTiles: Array<DashboardTile>, newTile: DashboardTile) { let changed = false; const newTiles = oldTiles.map(tile => { if (tile.id === newTile.id) { changed = changed || tile.colSpan !== newTile.colSpan || tile.column !== newTile.column || tile.hidden !== newTile.hidden || tile.row !== newTile.row || tile.rowSpan !== newTile.rowSpan; return newTile; } else if (collides(tile, newTile)) { changed = true; return { id: tile.id, colSpan: tile.colSpan, rowSpan: tile.rowSpan, }; } return tile; }); return changed ? newTiles : oldTiles; } /** * Dashboard component. */ export class Dashboard extends React.Component<DashboardProps, DashboardState> { private setters: Array<(e: GridAreaTapEvent) => void> = []; private layout: GridLayout; private activeTile: | { node: HTMLElement; x: number; y: number; width: number; height: number; index: number; current: DashboardTile; } | undefined; constructor(props: DashboardProps) { super(props); const { defaultTiles = [] } = props; this.state = { tiles: [...defaultTiles], live: undefined, }; } UNSAFE_componentWillReceiveProps(nextProps: DashboardProps) { const { defaultTiles: currTiles = [] } = this.props; const { defaultTiles: nextTiles = [] } = nextProps; if (notEqual(currTiles, nextTiles)) { this.setState({ tiles: [...nextTiles], live: undefined, }); } } private finishDrag(newTile: DashboardTile) { const { onChange } = this.props; const { tiles: oldTiles } = this.state; const newTiles = changeTile(oldTiles, newTile); this.activeTile = undefined; if (newTiles !== oldTiles) { this.setState({ tiles: newTiles, live: undefined, }); if (typeof onChange === 'function') { onChange({ tile: newTile, tiles: newTiles, }); } } else { this.setState({ live: undefined, }); } } private dragTile = (e: InteractiveSurfaceChangeEvent) => { const { activeTile } = this; if (activeTile) { const node = activeTile.node; const current = activeTile.current; if (!e.moved) { // don't do anything (yet) } else if (e.active) { const style = node.style; style.left = calc(e.x, activeTile.x, e.rect.width, activeTile.width); style.top = calc(e.y, activeTile.y, e.rect.height, activeTile.height); this.previewDrag(e.x, e.y, current); } else { const pos = this.getTargetPosition(e.x, e.y, current); resetStyle(node); this.finishDrag({ ...current, column: pos.column, row: pos.row, }); } } else { e.release(); } }; private previewDrag(h: number, v: number, tile: DashboardTile) { const active = this.activeTile; const { preview } = this.props; const { live, tiles } = this.state; if (preview && active && live) { const current = active.current; const pos = this.getTargetPosition(h, v, tile); const last = live[active.index]; if (pos.column !== last.column || pos.row !== last.row) { this.setState({ live: changeTile(tiles, { ...current, column: pos.column, row: pos.row, }), }); } } } private getTargetPosition(h: number, v: number, tile: DashboardTile) { const { columns, rows } = this.layout; const { colSpan = 1, rowSpan = 1 } = tile; const { x, y, width, height } = this.activeTile || defaultActiveTile; const totalRows = rows.length; const totalColumns = columns.length; const columnOffset = ~~((x * colSpan) / width); const rowOffset = ~~((y * rowSpan) / height); return { column: clamp(0, ~~(h * totalColumns) - columnOffset, totalColumns - colSpan), row: clamp(0, ~~(v * totalRows) - rowOffset, totalRows - rowSpan), }; } private setActiveTile(e: GridAreaTapEvent, index: number) { const { disabled } = this.props; const { tiles } = this.state; const current = tiles[index]; if (!disabled) { this.activeTile = { ...e, index, current, }; const style = e.node.style; style.cursor = 'move'; style.position = 'absolute'; style.width = `${e.width}px`; style.height = `${e.height}px`; style.zIndex = '100000000'; this.setState({ live: tiles, }); } } private setLayout = ({ layout }: { layout: GridLayout }) => { this.layout = layout; }; render() { const { columnWidth, columnCount = 5, rowHeight, rowCount, spacing = 10, theme, children, disabled, preview, defaultTiles: _0, onChange: _1, emptyTiles, ...props } = this.props; const { tiles, live } = this.state; const currentTiles = live || tiles; const columns = repeat(columnCount, columnWidth); const rows = repeat(rowCount, rowHeight); const active = this.activeTile; return ( <InteractiveSurface theme={theme} onChange={this.dragTile} disabled={disabled}> <Grid theme={theme} rows={rows} columns={columns} spacing={`${spacing}px`} showEmptyCells={emptyTiles} onLayout={this.setLayout} {...props}> {React.Children.map(children, (child, index) => { const tile = currentTiles[index]; const setters = this.setters; if (setters[index] === undefined) { setters[index] = e => this.setActiveTile(e, index); } return ( tile && ( <GridArea key={tile.id} theme={theme} onTap={setters[index]} column={tile.column} colSpan={tile.colSpan} rowSpan={tile.rowSpan} hidden={tile.hidden} row={tile.row}> {child} </GridArea> ) ); })} {preview && active && getPreview(preview, currentTiles[active.index])} </Grid> </InteractiveSurface> ); } }
the_stack
import {TypedEvent} from "../../../common/events"; import {cast, server} from "../../../socket/socketClient"; import * as editBatcher from "./editBatcher"; import * as utils from "../../../common/utils"; import * as classifierCache from "./classifierCache"; import {RefactoringsByFilePath, Refactoring} from "../../../common/types"; import * as state from "../../state/state"; import {EditorOptions} from "../../../common/types"; import * as monacoUtils from "../../monaco/monacoUtils"; import * as events from "../../../common/events"; /** * We extend the monaco editor model */ declare global { module monaco { module editor { interface IReadOnlyModel { /** * keep `filePath` * Beyond other things, it is critical to our tokenizer. **/ filePath?: string; /** * add a list of editors * - useful for restoring cursors if we edit the model */ _editors: monaco.editor.ICodeEditor[]; /** * store the format code options so we can use them later */ _editorOptions: EditorOptions; } interface ICodeEditor { } } } } /** * Setup any additional languages */ import {setupMonacoTypecript} from "../../monaco/languages/typescript/monacoTypeScript"; setupMonacoTypecript(); import {setupMonacoJson} from "../../monaco/languages/json/monacoJson"; setupMonacoJson(); /** * Ext lookup */ const extLookup: { [ext: string]: monaco.languages.ILanguageExtensionPoint } = {}; monaco.languages.getLanguages().forEach(function(language) { // console.log(language); // DEBUG language.extensions.forEach(ext => { // ext is like `.foo`. We really want `foo` ext = ext.substr(1); extLookup[ext] = language; }) }); /** * Gets the mode for a give filePath (based on its ext) */ const getLanguage = (filePath: string): string => { const mode = extLookup[utils.getExt(filePath)]; return mode ? mode.id : 'plaintext'; } // to track the source of changes, local vs. network const localSourceId: string = utils.createId(); export type GetLinkedDocResponse = { doc: monaco.editor.IModel; editorOptions: EditorOptions } export function getLinkedDoc(filePath: string,editor: monaco.editor.ICodeEditor): Promise<GetLinkedDocResponse> { return getOrCreateDoc(filePath) .then(({doc, isJsOrTsFile, editorOptions}) => { // Everytime a typescript file is opened we ask for its output status (server pull) // On editing this happens automatically (server push) server.getJSOutputStatus({ filePath }).then(res => { if (res.inActiveProject) { state.fileOuputStatusUpdated(res.outputStatus); } }); /** Wire up the doc */ editor.setModel(doc); /** Add to list of editors */ doc._editors.push(editor); return {doc: doc, editorOptions: editorOptions}; }); } export function removeLinkedDoc(filePath:string, editor: monaco.editor.ICodeEditor){ editor.getModel()._editors = editor.getModel()._editors.filter(e => e != editor); // if this was the last editor using this model then we remove it from the cache as well // otherwise we might get a file even if its deleted from the server if (!editor.getModel()._editors.length){ docByFilePathPromised[filePath].then(x=>{ x.disposable.dispose(); delete docByFilePathPromised[filePath]; }) } } type DocPromiseResult = { doc: monaco.editor.IModel, isJsOrTsFile: boolean, editorOptions: EditorOptions, disposable: IDisposable, } let docByFilePathPromised: { [filePath: string]: Promise<DocPromiseResult> } = Object.create(null); function getOrCreateDoc(filePath: string): Promise<DocPromiseResult> { if (docByFilePathPromised[filePath]) { return docByFilePathPromised[filePath]; } else { return docByFilePathPromised[filePath] = server.openFile({ filePath: filePath }).then((res) => { const disposable = new events.CompositeDisposible(); let ext = utils.getExt(filePath); let isJsOrTsFile = utils.isJsOrTs(filePath); let language = getLanguage(filePath); // console.log(res.editorOptions); // DEBUG // console.log(mode,supportedModesMap[ext]); // Debug mode // Add to classifier cache if (isJsOrTsFile) { classifierCache.addFile(filePath, res.contents); disposable.add({ dispose: () => classifierCache.removeFile(filePath) }); } // create the doc const doc = monaco.editor.createModel(res.contents, language); doc.setEOL(monaco.editor.EndOfLineSequence.LF); // The true eol is only with the file model at the backend. The frontend doesn't care 🌹 doc.filePath = filePath; doc._editors = []; doc._editorOptions = res.editorOptions; /** Susbcribe to editor options changing */ disposable.add(cast.editorOptionsChanged.on((res) => { if (res.filePath === filePath) { doc._editorOptions = res.editorOptions; } })); /** * We ignore edit notifications from monaco if *we* did the edit e.g. * - if the server sent the edit and we applied it. */ let countOfEditNotificationsToIgnore = 0; /** This is used for monaco edit operation version counting purposes */ let editorOperationCounter = 0; // setup to push doc changes to server disposable.add(doc.onDidChangeContent(evt => { // Keep the ouput status cache informed state.ifJSStatusWasCurrentThenMoveToOutOfDate({inputFilePath: filePath}); // if this edit is happening // because *we edited it due to a server request* // we should exit if (countOfEditNotificationsToIgnore) { countOfEditNotificationsToIgnore--; return; } let codeEdit: CodeEdit = { from: { line: evt.range.startLineNumber - 1, ch: evt.range.startColumn - 1 }, to: { line: evt.range.endLineNumber - 1, ch: evt.range.endColumn - 1 }, newText: evt.text, sourceId: localSourceId }; // Send the edit editBatcher.addToQueue(filePath, codeEdit); // Keep the classifier in sync if (isJsOrTsFile) { classifierCache.editFile(filePath, codeEdit) } })); // setup to get doc changes from server disposable.add(cast.didEdits.on(res=> { // console.log('got server edit', res.edit.sourceId,'our', sourceId) let codeEdits = res.edits; codeEdits.forEach(codeEdit => { // Easy exit for local edits getting echoed back if (res.filePath == filePath && codeEdit.sourceId !== localSourceId) { // Keep the classifier in sync if (isJsOrTsFile) { classifierCache.editFile(filePath, codeEdit); } // make the edits const editOperation: monaco.editor.IIdentifiedSingleEditOperation = { identifier: { major: editorOperationCounter++, minor: 0 }, text: codeEdit.newText, range: new monaco.Range( codeEdit.from.line + 1, codeEdit.from.ch + 1, codeEdit.to.line + 1, codeEdit.to.ch + 1 ), forceMoveMarkers: false, isAutoWhitespaceEdit: false, } /** Mark as ignoring before applying the edit */ countOfEditNotificationsToIgnore++; doc.pushEditOperations([], [editOperation], null); } }); })); // setup loading saved files changing on disk disposable.add(cast.savedFileChangedOnDisk.on((res) => { if (res.filePath == filePath && doc.getValue() !== res.contents) { // preserve cursor doc._editors.forEach(e=>{ const cursors = e.getSelections(); setTimeout(()=>{ e.setSelections(cursors); }) }) // Keep the classifier in sync if (isJsOrTsFile) { classifierCache.setContents(filePath, res.contents); } // Note that we use *mark as coming from server* so we don't go into doc.change handler later on :) countOfEditNotificationsToIgnore++; // NOTE: we don't do `setValue` as // - that creates a new tokenizer (we would need to use `window.creatingModelFilePath`) // - looses all undo history. // Instead we *replace* all the text that is there 🌹 const totalDocRange = doc.getFullModelRange(); monacoUtils.replaceRange({ range: totalDocRange, model: doc, newText: res.contents }); } })); // Finally return the doc const result: DocPromiseResult = { doc, isJsOrTsFile, editorOptions: res.editorOptions, disposable: disposable, }; return result; }); } } /** * Don't plan to export as giving others our true docs can have horrible consequences if they mess them up */ function getOrCreateDocs(filePaths: string[]): Promise<{ [filePath: string]: monaco.editor.IModel }> { let promises = filePaths.map(fp => getOrCreateDoc(fp)); return Promise.all(promises).then(docs => { let res: { [filePath: string]: monaco.editor.IModel } = {}; docs.forEach(({doc}) => res[doc.filePath] = doc); return res; }); } export function applyRefactoringsToTsDocs(refactorings: RefactoringsByFilePath) { let filePaths = Object.keys(refactorings); getOrCreateDocs(filePaths).then(docsByFilePath => { filePaths.forEach(fp=> { let doc = docsByFilePath[fp]; let changes = refactorings[fp]; for (let change of changes) { const from = classifierCache.getLineAndCharacterOfPosition(fp, change.span.start); const to = classifierCache.getLineAndCharacterOfPosition(fp, change.span.start + change.span.length); monacoUtils.replaceRange({ model: doc, range: { startLineNumber: from.line + 1, startColumn: from.ch + 1, endLineNumber: to.line + 1, endColumn: to.ch + 1 }, newText: change.newText }); } }); }); }
the_stack
import { TabsService, ITab, ITabAPI } from 'chipmunk-client-material'; import { Subscription } from './service.electron.ipc'; import { Session } from '../controller/session/session'; import { IService } from '../interfaces/interface.service'; import { Subject, Subscription as SubscriptionRX } from 'rxjs'; import { IDefaultView } from '../states/state.default'; import { IAPI, IPopup, IComponentDesc, ISettingsAPI } from 'chipmunk.client.toolkit'; import { copyTextToClipboard } from '../controller/helpers/clipboard'; import { fullClearRowStr } from '../controller/helpers/row.helpers'; import { ISearchSettings } from '../components/views/search/component'; import EventsSessionService from './standalone/service.events.session'; import ServiceElectronIpc, { IPC } from './service.electron.ipc'; import SourcesService from './service.sources'; import HotkeysService from './service.hotkeys'; import PluginsService from './service.plugins'; import PopupsService from './standalone/service.popups'; import OutputRedirectionsService from './standalone/service.output.redirections'; import LayoutStateService from './standalone/service.layout.state'; import SettingsService from './service.settings'; import * as Toolkit from 'chipmunk.client.toolkit'; export { ITabAPI }; export { ControllerSessionTabSearch } from '../controller/session/dependencies/search/controller.session.tab.search'; export type TSessionGuid = string; export type TSidebarTabOpener = ( guid: string, session: string | undefined, silence: boolean, ) => Error | undefined; export type TToolbarTabOpener = ( guid: string, session: string | undefined, silence: boolean, ) => Promise<void>; export type TNotificationOpener = (notification: Toolkit.INotification) => void; export interface IServiceSubjects { onSessionChange: Subject<Session | undefined>; onSessionClosed: Subject<string>; } export interface ICustomTab { id: string; title: string; component: IComponentDesc; } export class TabsSessionsService implements IService { private _logger: Toolkit.Logger = new Toolkit.Logger('TabsSessionsService'); private _sessions: Map<TSessionGuid, Session | ICustomTab> = new Map(); private _sources: Map<TSessionGuid, number> = new Map(); private _tabsService: TabsService = new TabsService(); private _subscriptions: { [key: string]: Subscription | SubscriptionRX } = {}; private _currentSessionGuid: string | undefined; private _sessionsEventsHub: Toolkit.ControllerSessionsEvents = new Toolkit.ControllerSessionsEvents(); private _sidebarTabOpener: TSidebarTabOpener | undefined; private _toolbarTabOpener: TToolbarTabOpener | undefined; private _notificationOpener: TNotificationOpener | undefined; private _defaultToolbarApps: Toolkit.IDefaultTabsGuids | undefined; private _searchSettings: { [guid: string]: ISearchSettings } = {}; private _defaults: { views: IDefaultView[]; } = { views: [], }; constructor() { this.getPluginAPI = this.getPluginAPI.bind(this); // Delivering API getter into Plugin Service here to escape from circular dependencies // (which will happen if try to access to this service from Plugin Service) PluginsService.setPluginAPIGetter(this.getPluginAPI); // Listen stream events this._subscriptions.onStreamUpdated = ServiceElectronIpc.subscribe( IPC.StreamUpdated, this._ipc_onStreamUpdated.bind(this), ); this._subscriptions.onSearchUpdated = ServiceElectronIpc.subscribe( IPC.SearchUpdated, this._ipc_onSearchUpdated.bind(this), ); } public init(): Promise<void> { return new Promise((resolve) => { this._subscriptions.onSessionTabChanged = this._tabsService .getObservable() .active.subscribe(this._onSessionTabSwitched.bind(this)); this._subscriptions.onSessionTabClosed = this._tabsService .getObservable() .removed.subscribe(this._onSessionTabClosed.bind(this)); this._subscriptions.onNewTab = HotkeysService.getObservable().newTab.subscribe( this._onNewTab.bind(this), ); this._subscriptions.onCloseTab = HotkeysService.getObservable().closeTab.subscribe( this._onCloseTab.bind(this), ); this._subscriptions.onNextTab = HotkeysService.getObservable().nextTab.subscribe( this._onNextTab.bind(this), ); this._subscriptions.onPrevTab = HotkeysService.getObservable().prevTab.subscribe( this._onPrevTab.bind(this), ); this._subscriptions.onCtrlC = HotkeysService.getObservable().ctrlC.subscribe( this._onCtrlC.bind(this), ); this._subscriptions.RenderSessionAddRequest = ServiceElectronIpc.subscribe( IPC.RenderSessionAddRequest, this._ipc_RenderSessionAddRequest.bind(this), ); const current = this._currentSessionGuid === undefined ? undefined : this._sessions.get(this._currentSessionGuid); OutputRedirectionsService.init(current instanceof Session ? current : undefined); resolve(); }); } public getName(): string { return 'TabsSessionsService'; } public destroy() { Object.keys(this._subscriptions).forEach((key: string) => { this._subscriptions[key].unsubscribe(); }); } public setSidebarTabOpener(opener: TSidebarTabOpener) { this._sidebarTabOpener = opener; } public setToolbarTabOpener(opener: TToolbarTabOpener, defaults: Toolkit.IDefaultTabsGuids) { this._defaultToolbarApps = defaults; this._toolbarTabOpener = opener; } public setNotificationOpener(opener: TNotificationOpener) { this._notificationOpener = opener; } public setDefaultViews(views: IDefaultView[]) { this._defaults.views = views; } public isTabExist(guid: string): boolean { return this._sessions.has(guid); } public add(custom?: ICustomTab): Promise<Session | ICustomTab> { return new Promise((resolve, reject) => { let guid: string = custom !== undefined ? custom.id : Toolkit.guid(); if (this._sessions.has(guid)) { return reject(new Error(`Tab guid "${guid}" already exist`)); } if (custom === undefined) { ServiceElectronIpc.request<IPC.StreamAddResponse>( new IPC.StreamAddRequest({ guid: guid, }), IPC.StreamAddResponse, ) .then((response) => { if (response.error) { return reject( new Error(`Fail to init stream due error: ${response.error}`), ); } guid = response.guid; this._logger.env(`Stream "${guid}" is inited`); const session = new Session({ guid: guid, api: this.getPluginAPI(undefined), sessionsEventsHub: this._sessionsEventsHub, }); session .init() .then(() => { const tabAPI: ITabAPI | undefined = this._tabsService.add({ guid: guid, name: 'New', active: true, content: { factory: this._defaults.views[0].component, inputs: { session: session, getTabAPI: (): ITabAPI | undefined => { return tabAPI; }, }, }, }); this._subscriptions[`onSourceChanged:${guid}`] = session .getObservable() .onSourceChanged.subscribe( this._onSourceChanged.bind(this, guid), ); this._sessions.set(guid, session); session.setTabAPI(tabAPI); this._sessionsEventsHub.emit().onSessionOpen(guid); this.setActive(guid); resolve(session); }) .catch((err: Error) => { reject( new Error( this._logger.error( `Fail to init session due error: ${err.message}`, ), ), ); }); }) .catch((error: Error) => { reject(error); }); } else { let tabAPI: ITabAPI | undefined; custom.component.inputs.getTabAPI = (): ITabAPI | undefined => { return tabAPI; }; this._sessions.set(guid, custom); tabAPI = this._tabsService.add({ guid: guid, name: custom.title, active: true, content: custom.component, }); this.setActive(guid); resolve(custom); } }); } public getTabsService(): TabsService { return this._tabsService; } public getSessionController(session?: string): Session | Error { if (session === undefined) { session = this._currentSessionGuid; } if (session === undefined) { return new Error(`No session guid is provided`); } const controller: Session | ICustomTab | undefined = this._sessions.get(session); if (!(controller instanceof Session)) { return new Error(`Fail to find defiend session "${session}"`); } return controller; } public setActive(guid: string) { if (guid === this._currentSessionGuid) { return; } const session: Session | ICustomTab | undefined = this._sessions.get(guid); if (session === undefined) { this._logger.warn(`Cannot fild session ${guid}. Cannot make this session active.`); return; } this._currentSessionGuid = guid; if (session instanceof Session) { LayoutStateService.unlock(); session.setActive(); ServiceElectronIpc.send(new IPC.StreamSetActive({ guid: this._currentSessionGuid })) .then(() => { EventsSessionService.getSubject().onSessionChange.next(session); this._sessionsEventsHub.emit().onSessionChange(guid); }) .catch((error: Error) => { this._logger.warn( `Fail to send notification about active session due error: ${error.message}`, ); }); } else { LayoutStateService.lock(); ServiceElectronIpc.send(new IPC.StreamSetActive({ guid: this._currentSessionGuid })) .then(() => { EventsSessionService.getSubject().onSessionChange.next(undefined); this._sessionsEventsHub.emit().onSessionChange(undefined); }) .catch((error: Error) => { this._logger.warn( `Fail to send notification about active session due error: ${error.message}`, ); }); } this._tabsService.setActive(this._currentSessionGuid); } public getActive(): Session | undefined { const controller: Session | ICustomTab | undefined = this._currentSessionGuid === undefined ? undefined : this._sessions.get(this._currentSessionGuid); return !(controller instanceof Session) ? undefined : controller; } public getEmpty(): Session | undefined { let target: Session | ICustomTab | undefined = this._currentSessionGuid === undefined ? undefined : this._sessions.get(this._currentSessionGuid); if (target instanceof Session) { return target; } target = undefined; this._sessions.forEach((controller: Session | ICustomTab) => { if ( controller instanceof Session && controller.getStreamOutput().getRowsCount() === 0 ) { target = controller; } }); return target; } public getSessionEventsHub(): Toolkit.ControllerSessionsEvents { return this._sessionsEventsHub; } public bars(): { openSidebarApp: (appId: string, openTabOnly: boolean) => void; openToolbarApp: (appId: string, openTabOnly: boolean) => Promise<void>; getDefsToolbarApps: () => Toolkit.IDefaultTabsGuids | undefined; } { const self = this; return { openSidebarApp: (appId: string, openTabOnly: boolean = false) => { const tab = self._tabsService.getActiveTab(); if (self._sidebarTabOpener === undefined || tab === undefined) { return; } LayoutStateService.sidebarMax(); self._sidebarTabOpener(appId, tab.guid, openTabOnly); }, openToolbarApp: (appId: string, openTabOnly: boolean = false): Promise<void> => { const tab = self._tabsService.getActiveTab(); return new Promise((resolve, reject) => { if (self._toolbarTabOpener === undefined || tab === undefined) { this._logger.error( `Cannot open Toolbar because ${ this._toolbarTabOpener === undefined ? `opener isn't inited` : `no active session` }`, ); return resolve(); //return reject(new Error(`Toolbar API isn't inited or no active tab`)); } LayoutStateService.toolbarMax(); self._toolbarTabOpener(appId, tab.guid, openTabOnly) .then(resolve) .catch(reject); }); }, getDefsToolbarApps: (): Toolkit.IDefaultTabsGuids | undefined => { return self._defaultToolbarApps; }, }; } public getPluginAPI(pluginId: number | undefined): IAPI { const self = this; return { getIPC: pluginId === undefined ? () => undefined : () => { const plugin = PluginsService.getPluginById(pluginId); if (plugin === undefined) { return undefined; } return plugin.ipc; }, getSettingsAPI: () => { return SettingsService.getPluginsAPI(); }, getActiveSessionId: () => { const controller: Session | undefined = self.getActive(); return controller === undefined ? undefined : controller.getGuid(); }, addOutputInjection: ( injection: Toolkit.IComponentInjection, type: Toolkit.EViewsTypes, ) => { const controller: Session | undefined = self.getActive(); return controller === undefined ? undefined : controller.addOutputInjection(injection, type); }, removeOutputInjection: (id: string, type: Toolkit.EViewsTypes) => { const controller: Session | undefined = self.getActive(); return controller === undefined ? undefined : controller.removeOutputInjection(id, type); }, getViewportEventsHub: () => { const controller: Session | undefined = self.getActive(); return controller === undefined ? undefined : controller.getViewportEventsHub(); }, getSessionsEventsHub: () => { return self._sessionsEventsHub; }, addPopup: (popup: IPopup) => { return PopupsService.add(popup); }, removePopup: (guid: string) => { PopupsService.remove(guid); }, setSidebarTitleInjection: (component: IComponentDesc | undefined) => { EventsSessionService.getSubject().onSidebarTitleInjection.next(component); }, openSidebarApp: self.bars().openSidebarApp, openToolbarApp: self.bars().openToolbarApp, getDefaultToolbarAppsIds: (): Toolkit.IDefaultTabsGuids => { return Object.assign({}, self._defaultToolbarApps); }, addNotification: (notification: Toolkit.INotification) => { if (self._notificationOpener === undefined) { return; } self._notificationOpener(notification); }, }; } public setSearchSettings(guid: string, settings: ISearchSettings) { this._searchSettings[guid] = settings; } public getSearchSettings(guid: string): ISearchSettings | undefined { return this._searchSettings[guid]; } private _onSourceChanged(guid: string, sourceId: number) { if (typeof sourceId !== 'number' || sourceId < 0) { return; } const current: number | undefined = this._sources.get(guid); if (current === sourceId) { return; } const name: string | undefined = SourcesService.getSourceName(sourceId); if (typeof name !== 'string' || name.trim() === '') { return; } this._sources.set(guid, sourceId); this._tabsService.setTitle(guid, name); } private _onSessionTabSwitched(tab: ITab) { if (tab.guid === undefined) { return; } if (!this._sessions.has(tab.guid)) { // Session isn't created yet, but creating return; } this.setActive(tab.guid); if (this.getSearchSettings(tab.guid) === undefined) { this.setSearchSettings(tab.guid, { casesensitive: false, wholeword: false, regexp: true, }); } } private _onSessionTabClosed(session: string) { // Get session controller const controller: Session | ICustomTab | undefined = this._sessions.get(session); if (controller === undefined) { this._logger.warn( `Fail to destroy session "${session}" because cannot find this session.`, ); return; } this._sessions.delete(session); if (controller instanceof Session) { controller .destroy() .then(() => { this._removeSession(session); this._logger.env(`Session "${session}" is destroyed`); }) .catch((error: Error) => { this._removeSession(session); this._logger.warn( `Fail to destroy session "${session}" due error: ${error.message}`, ); }); } else { this._removeSession(session); this._logger.env(`Session "${session}" is removed`); } this._removeSearchSettings(session); } private _removeSearchSettings(guid: string) { delete this._searchSettings[guid]; } private _removeSession(guid: string) { if (this._subscriptions[`onSourceChanged:${guid}`] !== undefined) { this._subscriptions[`onSourceChanged:${guid}`].unsubscribe(); } if (this._sessions.size === 0) { EventsSessionService.getSubject().onSessionChange.next(undefined); this._sessionsEventsHub.emit().onSessionChange(undefined); } EventsSessionService.getSubject().onSessionClosed.next(guid); this._sessionsEventsHub.emit().onSessionClose(guid); } private _onNewTab() { this.add(); } private _onCloseTab() { this._currentSessionGuid !== undefined && this._tabsService.remove(this._currentSessionGuid); } private _onNextTab() { this._tabsService.next(); } private _onPrevTab() { this._tabsService.prev(); } private _onCtrlC() { const window_selection = window.getSelection(); if (window_selection === null) { return; } if (window_selection.toString() !== '') { return; } const session = this.getActive(); if (session === undefined) { return; } OutputRedirectionsService.getOutputSelectionRanges(session.getGuid()) .then((selection) => { return session .getSessionStream() .getRowsSelection(selection) .then((rows) => { copyTextToClipboard(fullClearRowStr(rows.map((row) => row.str).join('\n'))); }) .catch((err: Error) => { this._logger.warn( `Fail get text selection for range ${selection.join('; ')} due error: ${ err.message }`, ); }); }) .catch((err: Error) => { this._logger.warn( `Fail to call OutputRedirectionsService.getOutputSelectionRanges due error: ${err.message}`, ); }); } private _ipc_RenderSessionAddRequest( message: IPC.RenderSessionAddRequest, response: (message: IPC.TMessage) => void, ) { this.add() .then((session: Session | ICustomTab) => { if (session instanceof Session) { response(new IPC.RenderSessionAddResponse({ session: session.getGuid() })); } else { response( new IPC.RenderSessionAddResponse({ session: '', error: `Fail to create Session. Has been gotten ICustomTab`, }), ); } }) .catch((error: Error) => { response(new IPC.RenderSessionAddResponse({ session: '', error: error.message })); }); } private _ipc_onStreamUpdated(message: IPC.StreamUpdated) { this._sessionsEventsHub .emit() .onStreamUpdated({ session: message.guid, rows: message.rowsCount }); } private _ipc_onSearchUpdated(message: IPC.SearchUpdated) { this._sessionsEventsHub .emit() .onSearchUpdated({ session: message.guid, rows: message.rowsCount }); } } export default new TabsSessionsService();
the_stack
export namespace SystemEvents { // Default Application export interface Application {} // Class /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * user account */ export interface User { /** * user's full name */ fullName(): string; /** * path to user's home directory */ homeDirectory(): any; /** * user's short name */ name(): string; /** * path to user's picture. Can be set for current user only! */ picturePath(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A collection of appearance preferences */ export interface AppearancePreferencesObject { /** * the overall look of buttons, menus and windows */ appearance(): any; /** * Is font smoothing on? */ fontSmoothing(): boolean; /** * the font size at or below which font smoothing is turned off */ fontSmoothingLimit(): number; /** * the method used for smoothing fonts */ fontSmoothingStyle(): any; /** * color used for hightlighting selected text and lists */ highlightColor(): any; /** * the number of recent applications to track */ recentApplicationsLimit(): number; /** * the number of recent documents to track */ recentDocumentsLimit(): number; /** * the number of recent servers to track */ recentServersLimit(): number; /** * the action performed by clicking the scroll bar */ scrollBarAction(): any; /** * Is smooth scrolling used? */ smoothScrolling(): boolean; /** * use dark menu bar and dock */ darkMode(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * user's CD and DVD insertion preferences */ export interface CDAndDvdPreferencesObject { /** * the blank CD insertion preference */ blankCD(): any; /** * the blank DVD insertion preference */ blankDVD(): any; /** * the blank BD insertion preference */ blankBD(): any; /** * the music CD insertion preference */ musicCD(): any; /** * the picture CD insertion preference */ pictureCD(): any; /** * the video DVD insertion preference */ videoDVD(): any; /** * the video BD insertion preference */ videoBD(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * a specific insertion preference */ export interface InsertionPreference { /** * application to launch or activate on the insertion of media */ customApplication(): any; /** * AppleScript to launch or activate on the insertion of media */ customScript(): any; /** * action to perform on media insertion */ insertionAction(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * desktop picture settings */ export interface Desktop { /** * name of the desktop */ name(): string; /** * unique identifier of the desktop */ id(): number; /** * number of seconds to wait between changing the desktop picture */ changeInterval(): any; /** * name of display on which this desktop appears */ displayName(): string; /** * path to file used as desktop picture */ picture(): any; /** * never, using interval, using login, after sleep */ pictureRotation(): number; /** * path to folder containing pictures for changing desktop background */ picturesFolder(): any; /** * turn on for random ordering of changing desktop pictures */ randomOrder(): boolean; /** * indicates whether the menu bar is translucent */ translucentMenuBar(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * user's dock preferences */ export interface DockPreferencesObject { /** * is the animation of opening applications on or off? */ animate(): boolean; /** * is autohiding the dock on or off? */ autohide(): boolean; /** * size/height of the items (between 0.0 (minimum) and 1.0 (maximum)) */ dockSize(): any; /** * is magnification on or off? */ magnification(): boolean; /** * maximum magnification size when magnification is on (between 0.0 (minimum) and 1.0 (maximum)) */ magnificationSize(): any; /** * minimization effect */ minimizeEffect(): any; /** * location on screen */ screenEdge(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * an item to be launched or opened at login */ export interface LoginItem { /** * Is the Login Item hidden when launched? */ hidden(): boolean; /** * the file type of the Login Item */ kind(): string; /** * the name of the Login Item */ name(): string; /** * the file system path to the Login Item */ path(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A collection of settings for configuring a connection */ export interface Configuration { /** * the name used to authenticate */ accountName(): string; /** * Is the configuration connected? */ connected(): boolean; /** * the unique identifier for the configuration */ id(): string; /** * the name of the configuration */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A collection of settings for a network interface */ export interface Interface { /** * configure the interface speed, duplex, and mtu automatically? */ automatic(): boolean; /** * the duplex setting half | full | full with flow control */ duplex(): string; /** * the unique identifier for the interface */ id(): string; /** * the type of interface */ kind(): string; /** * the MAC address for the interface */ MACAddress(): string; /** * the packet size */ mtu(): number; /** * the name of the interface */ name(): string; /** * ethernet speed 10 | 100 | 1000 */ speed(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A set of services */ export interface Location { /** * the unique identifier for the location */ id(): string; /** * the name of the location */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * the preferences for the current user's network */ export interface NetworkPreferencesObject { /** * the current location */ currentLocation(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A collection of settings for a network service */ export interface Service { /** * Is the service active? */ active(): boolean; /** * the currently selected configuration */ currentConfiguration(): any; /** * the unique identifier for the service */ id(): string; /** * the interface the service is built on */ interface(): any; /** * the type of service */ kind(): number; /** * the name of the service */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * an installed screen saver */ export interface ScreenSaver { /** * name of the screen saver module as displayed to the user */ displayedName(): string; /** * name of the screen saver module to be displayed */ name(): string; /** * path to the screen saver module */ path(): any; /** * effect to use when displaying picture-based screen savers (slideshow, collage, or mosaic) */ pictureDisplayStyle(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * screen saver settings */ export interface ScreenSaverPreferencesObject { /** * number of seconds of idle time before the screen saver starts; zero for never */ delayInterval(): number; /** * should the screen saver be shown only on the main screen? */ mainScreenOnly(): boolean; /** * is the screen saver running? */ running(): boolean; /** * should a clock appear over the screen saver? */ showClock(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Data in Audio format */ export interface AudioData {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A file containing data in Audio format */ export interface AudioFile {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * a collection of security preferences */ export interface SecurityPreferencesObject { /** * Is automatic login allowed? */ automaticLogin(): boolean; /** * Will the computer log out when inactive? */ logOutWhenInactive(): boolean; /** * The interval of inactivity after which the computer will log out */ logOutWhenInactiveInterval(): number; /** * Is a password required to unlock secure preferences? */ requirePasswordToUnlock(): boolean; /** * Is a password required to wake the computer from sleep or screen saver? */ requirePasswordToWake(): boolean; /** * Is secure virtual memory being used? */ secureVirtualMemory(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An alias in the file system */ export interface Alias { /** * the OSType identifying the application that created the alias */ creatorType(): any; /** * the application that will launch if the alias is opened */ defaultApplication(): any; /** * the OSType identifying the type of data contained in the alias */ fileType(): any; /** * The kind of alias, as shown in Finder */ kind(): string; /** * the version of the product (visible at the top of the "Get Info" window) */ productVersion(): string; /** * the short version of the application bundle referenced by the alias */ shortVersion(): string; /** * Is the alias a stationery pad? */ stationery(): boolean; /** * The type identifier of the alias */ typeIdentifier(): string; /** * the version of the application bundle referenced by the alias (visible at the bottom of the "Get Info" window) */ version(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The Classic domain in the file system */ export interface ClassicDomainObject { /** * The Apple Menu Items folder */ appleMenuFolder(): any; /** * The Control Panels folder */ controlPanelsFolder(): any; /** * The Control Strip Modules folder */ controlStripModulesFolder(): any; /** * The Classic Desktop folder */ desktopFolder(): any; /** * The Extensions folder */ extensionsFolder(): any; /** * The Fonts folder */ fontsFolder(): any; /** * The Launcher Items folder */ launcherItemsFolder(): any; /** * The Classic Preferences folder */ preferencesFolder(): any; /** * The Shutdown Items folder */ shutdownFolder(): any; /** * The StartupItems folder */ startupItemsFolder(): any; /** * The System folder */ systemFolder(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A disk in the file system */ export interface Disk { /** * the total number of bytes (free or used) on the disk */ capacity(): number; /** * Can the media be ejected (floppies, CD's, and so on)? */ ejectable(): boolean; /** * the file system format of this disk */ format(): any; /** * the number of free bytes left on the disk */ freeSpace(): number; /** * Ignore permissions on this disk? */ ignorePrivileges(): boolean; /** * Is the media a local volume (as opposed to a file server)? */ localVolume(): boolean; /** * the server on which the disk resides, AFP volumes only */ server(): any; /** * Is this disk the boot disk? */ startup(): boolean; /** * the zone in which the disk's server resides, AFP volumes only */ zone(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An item stored in the file system */ export interface DiskItem { /** * Is the disk item busy? */ busyStatus(): boolean; /** * the folder or disk which has this disk item as an element */ container(): any; /** * the date on which the disk item was created */ creationDate(): any; /** * the name of the disk item as displayed in the User Interface */ displayedName(): string; /** * the unique ID of the disk item */ id(): string; /** * the date on which the disk item was last modified */ modificationDate(): any; /** * the name of the disk item */ name(): string; /** * the extension portion of the name */ nameExtension(): string; /** * Is the disk item a package? */ packageFolder(): boolean; /** * the file system path of the disk item */ path(): string; /** * the actual space used by the disk item on disk */ physicalSize(): number; /** * the POSIX file system path of the disk item */ POSIXPath(): string; /** * the logical size of the disk item */ size(): number; /** * the URL of the disk item */ URL(): string; /** * Is the disk item visible? */ visible(): boolean; /** * the volume on which the disk item resides */ volume(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A domain in the file system */ export interface Domain { /** * The Application Support folder */ applicationSupportFolder(): any; /** * The Applications folder */ applicationsFolder(): any; /** * The Desktop Pictures folder */ desktopPicturesFolder(): any; /** * The Folder Action Scripts folder */ folderActionScriptsFolder(): any; /** * The Fonts folder */ fontsFolder(): any; /** * the unique identifier of the domain */ id(): string; /** * The Library folder */ libraryFolder(): any; /** * the name of the domain */ name(): string; /** * The Preferences folder */ preferencesFolder(): any; /** * The Scripting Additions folder */ scriptingAdditionsFolder(): any; /** * The Scripts folder */ scriptsFolder(): any; /** * The Shared Documents folder */ sharedDocumentsFolder(): any; /** * The Speakable Items folder */ speakableItemsFolder(): any; /** * The Utilities folder */ utilitiesFolder(): any; /** * The Automator Workflows folder */ workflowsFolder(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A file in the file system */ export interface File { /** * the OSType identifying the application that created the file */ creatorType(): any; /** * the application that will launch if the file is opened */ defaultApplication(): any; /** * the OSType identifying the type of data contained in the file */ fileType(): any; /** * The kind of file, as shown in Finder */ kind(): string; /** * the version of the product (visible at the top of the "Get Info" window) */ productVersion(): string; /** * the short version of the file */ shortVersion(): string; /** * Is the file a stationery pad? */ stationery(): boolean; /** * The type identifier of the file */ typeIdentifier(): string; /** * the version of the file (visible at the bottom of the "Get Info" window) */ version(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A file package in the file system */ export interface FilePackage {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A folder in the file system */ export interface Folder {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The local domain in the file system */ export interface LocalDomainObject {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The network domain in the file system */ export interface NetworkDomainObject {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The system domain in the file system */ export interface SystemDomainObject {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The user domain in the file system */ export interface UserDomainObject { /** * The user's Desktop folder */ desktopFolder(): any; /** * The user's Documents folder */ documentsFolder(): any; /** * The user's Downloads folder */ downloadsFolder(): any; /** * The user's Favorites folder */ favoritesFolder(): any; /** * The user's Home folder */ homeFolder(): any; /** * The user's Movies folder */ moviesFolder(): any; /** * The user's Music folder */ musicFolder(): any; /** * The user's Pictures folder */ picturesFolder(): any; /** * The user's Public folder */ publicFolder(): any; /** * The user's Sites folder */ sitesFolder(): any; /** * The Temporary Items folder */ temporaryItemsFolder(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Data in Movie format */ export interface MovieData { /** * the bounding rectangle of the movie file */ bounds(): any; /** * the dimensions the movie has when it is not scaled */ naturalDimensions(): any; /** * the preview duration of the movie file */ previewDuration(): number; /** * the preview time of the movie file */ previewTime(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A file containing data in Movie format */ export interface MovieFile {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An action that can be performed on the UI element */ export interface Action { /** * what the action does */ description(): string; /** * the name of the action */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A process launched from an application file */ export interface ApplicationProcess { /** * a reference to the application file from which this process was launched */ applicationFile(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An named data value associated with the UI element */ export interface Attribute { /** * the name of the attribute */ name(): string; /** * Can the attribute be set? */ settable(): boolean; /** * the current value of the attribute */ value(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A browser belonging to a window */ export interface Browser {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A busy indicator belonging to a window */ export interface BusyIndicator {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A button belonging to a window or scroll bar */ export interface Button {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A checkbox belonging to a window */ export interface Checkbox {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A color well belonging to a window */ export interface ColorWell {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A column belonging to a table */ export interface Column {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A combo box belonging to a window */ export interface ComboBox {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A process launched from an desk accessory file */ export interface DeskAccessoryProcess { /** * a reference to the desk accessory file from which this process was launched */ deskAccessoryFile(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A drawer that may be extended from a window */ export interface Drawer {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A group belonging to a window */ export interface Group {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A grow area belonging to a window */ export interface GrowArea {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An image belonging to a static text field */ export interface Image {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A incrementor belonging to a window */ export interface Incrementor {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A list belonging to a window */ export interface List {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A menu belonging to a menu bar item */ export interface Menu {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A menu bar belonging to a process */ export interface MenuBar {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A menu bar item belonging to a menu bar */ export interface MenuBarItem {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A menu button belonging to a window */ export interface MenuButton {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A menu item belonging to a menu */ export interface MenuItem {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A outline belonging to a window */ export interface Outline {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A pop over belonging to a window */ export interface PopOver {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A pop up button belonging to a window */ export interface PopUpButton {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A process running on this computer */ export interface Process { /** * Is the process high-level event aware (accepts open application, open document, print document, and quit)? */ acceptsHighLevelEvents(): boolean; /** * Does the process accept remote events? */ acceptsRemoteEvents(): boolean; /** * the architecture in which the process is running */ architecture(): string; /** * Does the process run exclusively in the background? */ backgroundOnly(): boolean; /** * the bundle identifier of the process' application file */ bundleIdentifier(): string; /** * Is the process running in the Classic environment? */ classic(): boolean; /** * the OSType of the creator of the process (the signature) */ creatorType(): string; /** * the name of the file from which the process was launched, as displayed in the User Interface */ displayedName(): string; /** * the file from which the process was launched */ file(): any; /** * the OSType of the file type of the process */ fileType(): string; /** * Is the process the frontmost process */ frontmost(): boolean; /** * Does the process have a scripting terminology, i.e., can it be scripted? */ hasScriptingTerminology(): boolean; /** * The unique identifier of the process */ id(): number; /** * the name of the process */ name(): string; /** * the number of bytes currently used in the process' partition */ partitionSpaceUsed(): number; /** * the short name of the file from which the process was launched */ shortName(): any; /** * the size of the partition with which the process was launched */ totalPartitionSize(): number; /** * The Unix process identifier of a process running in the native environment, or -1 for a process running in the Classic environment */ unixId(): number; /** * Is the process' layer visible? */ visible(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A progress indicator belonging to a window */ export interface ProgressIndicator {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A radio button belonging to a window */ export interface RadioButton {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A radio button group belonging to a window */ export interface RadioGroup {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A relevance indicator belonging to a window */ export interface RelevanceIndicator {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A row belonging to a table */ export interface Row {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A scroll area belonging to a window */ export interface ScrollArea {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A scroll bar belonging to a window */ export interface ScrollBar {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A sheet displayed over a window */ export interface Sheet {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A slider belonging to a window */ export interface Slider {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A splitter belonging to a window */ export interface Splitter {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A splitter group belonging to a window */ export interface SplitterGroup {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A static text field belonging to a window */ export interface StaticText {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A tab group belonging to a window */ export interface TabGroup {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A table belonging to a window */ export interface Table {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A text area belonging to a window */ export interface TextArea {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A text field belonging to a window */ export interface TextField {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A toolbar belonging to a window */ export interface Toolbar {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A piece of the user interface of a process */ export interface UIElement { /** * a more complete description of the UI element and its capabilities */ accessibilityDescription(): any; /** * the class of the UI Element, which identifies it function */ class(): any; /** * the accessibility description, if available; otherwise, the role description */ description(): any; /** * Is the UI element enabled? ( Does it accept clicks? ) */ enabled(): any; /** * a list of every UI element contained in this UI element and its child UI elements, to the limits of the tree */ entireContents(): any; /** * Is the focus on this UI element? */ focused(): any; /** * an elaborate description of the UI element and its capabilities */ help(): any; /** * the maximum value that the UI element can take on */ maximumValue(): any; /** * the minimum value that the UI element can take on */ minimumValue(): any; /** * the name of the UI Element, which identifies it within its container */ name(): string; /** * the orientation of the UI element */ orientation(): any; /** * the position of the UI element */ position(): any; /** * an encoded description of the UI element and its capabilities */ role(): string; /** * a more complete description of the UI element's role */ roleDescription(): string; /** * Is the UI element selected? */ selected(): any; /** * the size of the UI element */ size(): any; /** * an encoded description of the UI element and its capabilities */ subrole(): any; /** * the title of the UI element as it appears on the screen */ title(): string; /** * the current value of the UI element */ value(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A value indicator ( thumb or slider ) belonging to a scroll bar */ export interface ValueIndicator {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A file containing data in Property List format */ export interface PropertyListFile {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A data blob */ export interface Data {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A unit of data in Property List format */ export interface PropertyListItem { /** * the kind of data stored in the property list item: boolean/data/date/list/number/record/string */ kind(): any; /** * the name of the property list item ( if any ) */ name(): string; /** * the text representation of the property list data */ text(): string; /** * the value of the property list item */ value(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A unit of user data in a QuickTime file */ export interface Annotation { /** * the full text of the annotation */ fullText(): string; /** * the unique identifier of the annotation */ id(): string; /** * the name of the annotation */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Data in QuickTime format */ export interface QuickTimeData { /** * will the movie automatically start playing? (saved with QuickTime file) */ autoPlay(): boolean; /** * will the movie automatically start presenting? (saved with QuickTime file) */ autoPresent(): boolean; /** * will the player automatically quit when done playing? (saved with QuickTime file) */ autoQuitWhenDone(): boolean; /** * the creation time of the QuickTime file */ creationTime(): any; /** * the size of the QuickTime file data */ dataSize(): number; /** * the duration of the QuickTime file, in terms of the time scale */ duration(): number; /** * the internet location to open when clicking on the movie (overrides track hrefs) */ href(): string; /** * keep playing the movie in a loop? */ looping(): boolean; /** * the modification time of the QuickTime file */ modificationTime(): any; /** * the preferred rate of the QuickTime file */ preferredRate(): number; /** * the preferred volume of the QuickTime file */ preferredVolume(): number; /** * mode in which the movie will be presented */ presentationMode(): any; /** * size at which the movie will be presented */ presentationSize(): any; /** * is this a stored streaming movie? */ storedStream(): boolean; /** * the time scale of the QuickTime file */ timeScale(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A file containing data in QuickTime format */ export interface QuickTimeFile {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A track in a QuickTime file */ export interface Track { /** * the number of channels in the audio */ audioChannelCount(): number; /** * can the track be heard? */ audioCharacteristic(): boolean; /** * the sample rate of the audio in kHz */ audioSampleRate(): any; /** * the size of uncompressed audio samples in bits */ audioSampleSize(): number; /** * the creation time of the track */ creationTime(): any; /** * the data format */ dataFormat(): string; /** * the data rate (bytes/sec) of the track */ dataRate(): number; /** * the size of the track data */ dataSize(): number; /** * the current dimensions of the track */ dimensions(): any; /** * the duration of the track, in terms of the time scale */ duration(): number; /** * should this track be used when the movie is playing? */ enabled(): boolean; /** * is the track high quality? */ highQuality(): boolean; /** * the internet location to open when clicking on the track */ href(): string; /** * the name of the media in the track, in the current language (e.g., 'Sound', 'Video', 'Text', ...) */ kind(): string; /** * the modification time of the track */ modificationTime(): any; /** * the name of the track */ name(): string; /** * the time delay before this track starts playing */ startTime(): number; /** * the type of media in the track (e.g., 'soun', 'vide', 'text', ...) */ type(): string; /** * deprecated: use "type" instead ( included only to resolve a terminology conflict, script text will be updated upon compilation ) */ typeClass(): string; /** * the color depth of the video */ videoDepth(): number; /** * can the track be seen? */ visualCharacteristic(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A named value associated with a unit of data in XML format */ export interface XMLAttribute { /** * the name of the XML attribute */ name(): string; /** * the value of the XML attribute */ value(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Data in XML format */ export interface XMLData { /** * the unique identifier of the XML data */ id(): string; /** * the name of the XML data */ name(): string; /** * the text representation of the XML data */ text(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A unit of data in XML format */ export interface XMLElement { /** * the unique identifier of the XML element */ id(): string; /** * the name of the XML element */ name(): string; /** * the value of the XML element */ value(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A file containing data in XML format */ export interface XMLFile {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface PrintSettings { /** * the number of copies of a document to be printed */ copies(): number; /** * Should printed copies be collated? */ collating(): boolean; /** * the first page of the document to be printed */ startingPage(): number; /** * the last page of the document to be printed */ endingPage(): number; /** * number of logical pages laid across a physical page */ pagesAcross(): number; /** * number of logical pages laid out down a physical page */ pagesDown(): number; /** * the time at which the desktop printer should print the document */ requestedPrintTime(): any; /** * how errors are handled */ errorHandling(): any; /** * for fax number */ faxNumber(): string; /** * for target printer */ targetPrinter(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A class within a suite within a scripting definition */ export interface ScriptingClass { /** * The name of the class */ name(): string; /** * The unique identifier of the class */ id(): string; /** * The description of the class */ description(): string; /** * Is the class hidden? */ hidden(): boolean; /** * The plural name of the class */ pluralName(): string; /** * The name of the suite to which this class belongs */ suiteName(): string; /** * The class from which this class inherits */ superclass(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A command within a suite within a scripting definition */ export interface ScriptingCommand { /** * The name of the command */ name(): string; /** * The unique identifier of the command */ id(): string; /** * The description of the command */ description(): string; /** * The direct parameter of the command */ directParameter(): any; /** * Is the command hidden? */ hidden(): boolean; /** * The object or data returned by this command */ scriptingResult(): any; /** * The name of the suite to which this command belongs */ suiteName(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The scripting definition of the System Events applicaation */ export interface ScriptingDefinitionObject {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An element within a class within a suite within a scripting definition */ export interface ScriptingElement {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An enumeration within a suite within a scripting definition */ export interface ScriptingEnumeration { /** * The name of the enumeration */ name(): string; /** * The unique identifier of the enumeration */ id(): string; /** * Is the enumeration hidden? */ hidden(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An enumerator within an enumeration within a suite within a scripting definition */ export interface ScriptingEnumerator { /** * The name of the enumerator */ name(): string; /** * The unique identifier of the enumerator */ id(): string; /** * The description of the enumerator */ description(): string; /** * Is the enumerator hidden? */ hidden(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A parameter within a command within a suite within a scripting definition */ export interface ScriptingParameter { /** * The name of the parameter */ name(): string; /** * The unique identifier of the parameter */ id(): string; /** * The description of the parameter */ description(): string; /** * Is the parameter hidden? */ hidden(): boolean; /** * The kind of object or data specified by this parameter */ kind(): string; /** * Is the parameter optional? */ optional(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A property within a class within a suite within a scripting definition */ export interface ScriptingProperty { /** * The name of the property */ name(): string; /** * The unique identifier of the property */ id(): string; /** * The type of access to this property */ access(): any; /** * The description of the property */ description(): string; /** * Is the property's value an enumerator? */ enumerated(): boolean; /** * Is the property hidden? */ hidden(): boolean; /** * The kind of object or data returned by this property */ kind(): string; /** * Is the property's value a list? */ listed(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The result of a command within a suite within a scripting definition */ export interface ScriptingResultObject { /** * The description of the property */ description(): string; /** * Is the scripting result's value an enumerator? */ enumerated(): boolean; /** * The kind of object or data returned by this property */ kind(): string; /** * Is the scripting result's value a list? */ listed(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A suite within a scripting definition */ export interface ScriptingSuite { /** * The name of the suite */ name(): string; /** * The unique identifier of the suite */ id(): string; /** * The description of the suite */ description(): string; /** * Is the suite hidden? */ hidden(): boolean; } // CLass Extension /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application { /** * the time in seconds the application will idle before quitting; if set to zero, idle time will not cause the application to quit */ quitDelay(): number; /** * Is the Script menu installed in the menu bar? */ scriptMenuEnabled(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application { /** * the currently logged in user */ currentUser(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application { /** * a collection of appearance preferences */ appearancePreferences(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application { /** * the preferences for the current user when a CD or DVD is inserted */ CDAndDvdPreferences(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application { /** * the primary desktop */ currentDesktop(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application { /** * the preferences for the current user's dock */ dockPreferences(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application { /** * the preferences for the current user's network */ networkPreferences(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application { /** * the currently selected screen saver */ currentScreenSaver(): any; /** * the preferences common to all screen savers */ screenSaverPreferences(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application { /** * a collection of security preferences */ securityPreferences(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The Disk-Folder-File specific extensions to the application */ export interface Application { /** * The Application Support folder */ applicationSupportFolder(): any; /** * The user's Applications folder */ applicationsFolder(): any; /** * the collection of folders belonging to the Classic System */ classicDomain(): any; /** * The user's Desktop folder */ desktopFolder(): any; /** * The Desktop Pictures folder */ desktopPicturesFolder(): any; /** * The user's Documents folder */ documentsFolder(): any; /** * The user's Downloads folder */ downloadsFolder(): any; /** * The user's Favorites folder */ favoritesFolder(): any; /** * The user's Folder Action Scripts folder */ folderActionScriptsFolder(): any; /** * The Fonts folder */ fontsFolder(): any; /** * The Home folder of the currently logged in user */ homeFolder(): any; /** * The Library folder */ libraryFolder(): any; /** * the collection of folders residing on the Local machine */ localDomain(): any; /** * The user's Movies folder */ moviesFolder(): any; /** * The user's Music folder */ musicFolder(): any; /** * the collection of folders residing on the Network */ networkDomain(): any; /** * The user's Pictures folder */ picturesFolder(): any; /** * The user's Preferences folder */ preferencesFolder(): any; /** * The user's Public folder */ publicFolder(): any; /** * The Scripting Additions folder */ scriptingAdditionsFolder(): any; /** * The user's Scripts folder */ scriptsFolder(): any; /** * The Shared Documents folder */ sharedDocumentsFolder(): any; /** * The user's Sites folder */ sitesFolder(): any; /** * The Speakable Items folder */ speakableItemsFolder(): any; /** * the disk from which Mac OS X was loaded */ startupDisk(): any; /** * the collection of folders belonging to the System */ systemDomain(): any; /** * The Temporary Items folder */ temporaryItemsFolder(): any; /** * The user's Trash folder */ trash(): any; /** * the collection of folders belonging to the User */ userDomain(): any; /** * The Utilities folder */ utilitiesFolder(): any; /** * The Automator Workflows folder */ workflowsFolder(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application { /** * Are UI element events currently being processed? */ UIElementsEnabled(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A window belonging to a process */ export interface Window { /** * a more complete description of the window and its capabilities */ accessibilityDescription(): any; /** * the class of the window, which identifies its function */ class(): any; /** * the accessibility description, if available; otherwise, the role description */ description(): any; /** * Is the window enabled? ( Does it accept clicks? ) */ enabled(): any; /** * a list of every UI element contained in this window and its child UI elements, to the limits of the tree */ entireContents(): any; /** * Is the focus on this window? */ focused(): any; /** * an elaborate description of the window and its capabilities */ help(): any; /** * the maximum value that the UI element can take on */ maximumValue(): any; /** * the minimum value that the UI element can take on */ minimumValue(): any; /** * the name of the window, which identifies it within its container */ name(): string; /** * the orientation of the window */ orientation(): any; /** * the position of the window */ position(): any; /** * an encoded description of the window and its capabilities */ role(): string; /** * a more complete description of the window's role */ roleDescription(): string; /** * Is the window selected? */ selected(): any; /** * the size of the window */ size(): any; /** * an encoded description of the window and its capabilities */ subrole(): any; /** * the title of the window as it appears on the screen */ title(): string; /** * the current value of the window */ value(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface PropertyListItem {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The Folder Actions specific extensions to the folder class */ export interface Folder {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The System Events application */ export interface Application { /** * The scripting definition of the System Events application */ scriptingDefinition(): any; } // Records // Function options /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MoveOptionalParameter { /** * The new location for the disk item(s). */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface RestartOptionalParameter { /** * Is the user defined state saving preference followed? */ stateSavingPreference?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ShutDownOptionalParameter { /** * Is the user defined state saving preference followed? */ stateSavingPreference?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ClickOptionalParameter { /** * when sent to a "process" object, the { x, y } location at which to click, in global coordinates */ at?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface KeyCodeOptionalParameter { /** * modifiers with which the key codes are to be entered */ using?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface KeystrokeOptionalParameter { /** * modifiers with which the keystrokes are to be entered */ using?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface AttachActionToOptionalParameter { /** * a file containing the script to attach */ using: string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface DoFolderActionOptionalParameter { /** * the folder action message to process */ folderActionCode: any; /** * a list of items for the folder action message to process */ withItemList?: any; /** * the new window size for the folder action message to process */ withWindowSize?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface EditActionOfOptionalParameter { /** * ...or the name of the action to edit */ usingActionName?: string; /** * the index number of the action to edit... */ usingActionNumber?: number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface RemoveActionFromOptionalParameter { /** * ...or the name of the action to remove */ usingActionName?: string; /** * the index number of the action to remove... */ usingActionNumber?: number; } } export interface SystemEvents extends SystemEvents.Application { // Functions /** * Discard the results of a bounded update session with one or more files. * */ abortTransaction(): void; /** * Begin a bounded update session with one or more files. * @return undefined */ beginTransaction(): number; /** * Apply the results of a bounded update session with one or more files. * */ endTransaction(): void; /** * connect a configuration or service * @param directParameter a configuration or service * @return undefined */ connect(directParameter: {}, ): SystemEvents.Configuration; /** * disconnect a configuration or service * @param directParameter a configuration or service * @return undefined */ disconnect(directParameter: {}, ): SystemEvents.Configuration; /** * start the screen saver * @param directParameter the object for the command * */ start(directParameter: {}, ): void; /** * stop the screen saver * @param directParameter the object for the command * */ stop(directParameter: {}, ): void; /** * Delete disk item(s). * @param directParameter The disk item(s) to be deleted. * */ delete(directParameter: SystemEvents.DiskItem, ): void; /** * Move disk item(s) to a new location. * @param directParameter The disk item(s) to be moved. * @param option * @return undefined */ move(directParameter: {}, option?: SystemEvents.MoveOptionalParameter): void; /** * Open disk item(s) with the appropriate application. * @param directParameter The disk item(s) to be opened. * @return undefined */ open(directParameter: {}, ): SystemEvents.File; /** * Log out the current user * */ logOut(): void; /** * Restart the computer * @param option * */ restart(option?: SystemEvents.RestartOptionalParameter): void; /** * Shut Down the computer * @param option * */ shutDown(option?: SystemEvents.ShutDownOptionalParameter): void; /** * Put the computer to sleep * */ sleep(): void; /** * cause the target process to behave as if the UI element were clicked * @param directParameter The UI element to be clicked. * @param option * @return undefined */ click(directParameter?: SystemEvents.UIElement, option?: SystemEvents.ClickOptionalParameter): void; /** * cause the target process to behave as if key codes were entered * @param directParameter The key code(s) to be sent. May be a list. * @param option * */ keyCode(directParameter: {}, option?: SystemEvents.KeyCodeOptionalParameter): void; /** * cause the target process to behave as if keystrokes were entered * @param directParameter The keystrokes to be sent. * @param option * */ keystroke(directParameter: string, option?: SystemEvents.KeystrokeOptionalParameter): void; /** * cause the target process to behave as if the action were applied to its UI element * @param directParameter The action to be performed. * @return undefined */ perform(directParameter: SystemEvents.Action, ): SystemEvents.Action; /** * set the selected property of the UI element * @param directParameter The UI element to be selected. * @return undefined */ select(directParameter: SystemEvents.UIElement, ): SystemEvents.UIElement; /** * Attach an action to a folder * @param directParameter the object for the command * @param option * @return undefined */ attachActionTo(directParameter: any, option?: SystemEvents.AttachActionToOptionalParameter): any; /** * List the actions attached to a folder * @param directParameter the object for the command * @return undefined */ attachedScripts(directParameter: any, ): void; /** * cause the target process to behave as if the UI element were cancelled * @param directParameter the object for the command * @return undefined */ cancel(directParameter: any, ): SystemEvents.UIElement; /** * cause the target process to behave as if the UI element were confirmed * @param directParameter the object for the command * @return undefined */ confirm(directParameter: any, ): SystemEvents.UIElement; /** * cause the target process to behave as if the UI element were decremented * @param directParameter the object for the command * @return undefined */ decrement(directParameter: any, ): SystemEvents.UIElement; /** * Send a folder action code to a folder action script * @param directParameter the object for the command * @param option * */ doFolderAction(directParameter: any, option?: SystemEvents.DoFolderActionOptionalParameter): void; /** * Execute an OSA script. * @param directParameter the object for the command * @return undefined */ doScript(directParameter: {}, ): any; /** * Edit an action of a folder * @param directParameter the object for the command * @param option * @return undefined */ editActionOf(directParameter: any, option?: SystemEvents.EditActionOfOptionalParameter): SystemEvents.File; /** * cause the target process to behave as if the UI element were incremented * @param directParameter the object for the command * @return undefined */ increment(directParameter: any, ): SystemEvents.UIElement; /** * cause the target process to behave as if keys were held down * @param directParameter the object for the command * */ keyDown(directParameter: any, ): void; /** * cause the target process to behave as if keys were released * @param directParameter the object for the command * */ keyUp(directParameter: any, ): void; /** * cause the target process to behave as if the UI element were picked * @param directParameter the object for the command * @return undefined */ pick(directParameter: any, ): SystemEvents.UIElement; /** * Remove a folder action from a folder * @param directParameter the object for the command * @param option * @return undefined */ removeActionFrom(directParameter: any, option?: SystemEvents.RemoveActionFromOptionalParameter): any; }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { CancelJobRunCommand, CancelJobRunCommandInput, CancelJobRunCommandOutput, } from "./commands/CancelJobRunCommand"; import { CreateManagedEndpointCommand, CreateManagedEndpointCommandInput, CreateManagedEndpointCommandOutput, } from "./commands/CreateManagedEndpointCommand"; import { CreateVirtualClusterCommand, CreateVirtualClusterCommandInput, CreateVirtualClusterCommandOutput, } from "./commands/CreateVirtualClusterCommand"; import { DeleteManagedEndpointCommand, DeleteManagedEndpointCommandInput, DeleteManagedEndpointCommandOutput, } from "./commands/DeleteManagedEndpointCommand"; import { DeleteVirtualClusterCommand, DeleteVirtualClusterCommandInput, DeleteVirtualClusterCommandOutput, } from "./commands/DeleteVirtualClusterCommand"; import { DescribeJobRunCommand, DescribeJobRunCommandInput, DescribeJobRunCommandOutput, } from "./commands/DescribeJobRunCommand"; import { DescribeManagedEndpointCommand, DescribeManagedEndpointCommandInput, DescribeManagedEndpointCommandOutput, } from "./commands/DescribeManagedEndpointCommand"; import { DescribeVirtualClusterCommand, DescribeVirtualClusterCommandInput, DescribeVirtualClusterCommandOutput, } from "./commands/DescribeVirtualClusterCommand"; import { ListJobRunsCommand, ListJobRunsCommandInput, ListJobRunsCommandOutput } from "./commands/ListJobRunsCommand"; import { ListManagedEndpointsCommand, ListManagedEndpointsCommandInput, ListManagedEndpointsCommandOutput, } from "./commands/ListManagedEndpointsCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { ListVirtualClustersCommand, ListVirtualClustersCommandInput, ListVirtualClustersCommandOutput, } from "./commands/ListVirtualClustersCommand"; import { StartJobRunCommand, StartJobRunCommandInput, StartJobRunCommandOutput } from "./commands/StartJobRunCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { EMRContainersClient } from "./EMRContainersClient"; /** * <p>Amazon EMR on EKS provides a deployment option for Amazon EMR that allows you to run * open-source big data frameworks on Amazon Elastic Kubernetes Service (Amazon EKS). With * this deployment option, you can focus on running analytics workloads while Amazon EMR on * EKS builds, configures, and manages containers for open-source applications. For more * information about Amazon EMR on EKS concepts and tasks, see <a href="https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/emr-eks.html">What is Amazon EMR on EKS</a>.</p> * <p> * <i>Amazon EMR containers</i> is the API name for Amazon EMR on EKS. The * <code>emr-containers</code> prefix is used in the following scenarios: </p> * <ul> * <li> * <p>It is the prefix in the CLI commands for Amazon EMR on EKS. For example, <code>aws * emr-containers start-job-run</code>.</p> * </li> * <li> * <p>It is the prefix before IAM policy actions for Amazon EMR on EKS. For example, <code>"Action": [ * "emr-containers:StartJobRun"]</code>. For more information, see <a href="https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/security_iam_service-with-iam.html#security_iam_service-with-iam-id-based-policies-actions">Policy actions for Amazon EMR on EKS</a>.</p> * </li> * <li> * <p>It is the prefix used in Amazon EMR on EKS service endpoints. For example, <code>emr-containers.us-east-2.amazonaws.com</code>. For more * information, see <a href="https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/service-quotas.html#service-endpoints">Amazon EMR on EKS Service Endpoints</a>.</p> * </li> * </ul> */ export class EMRContainers extends EMRContainersClient { /** * <p>Cancels a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS.</p> */ public cancelJobRun( args: CancelJobRunCommandInput, options?: __HttpHandlerOptions ): Promise<CancelJobRunCommandOutput>; public cancelJobRun(args: CancelJobRunCommandInput, cb: (err: any, data?: CancelJobRunCommandOutput) => void): void; public cancelJobRun( args: CancelJobRunCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CancelJobRunCommandOutput) => void ): void; public cancelJobRun( args: CancelJobRunCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CancelJobRunCommandOutput) => void), cb?: (err: any, data?: CancelJobRunCommandOutput) => void ): Promise<CancelJobRunCommandOutput> | void { const command = new CancelJobRunCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster.</p> */ public createManagedEndpoint( args: CreateManagedEndpointCommandInput, options?: __HttpHandlerOptions ): Promise<CreateManagedEndpointCommandOutput>; public createManagedEndpoint( args: CreateManagedEndpointCommandInput, cb: (err: any, data?: CreateManagedEndpointCommandOutput) => void ): void; public createManagedEndpoint( args: CreateManagedEndpointCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateManagedEndpointCommandOutput) => void ): void; public createManagedEndpoint( args: CreateManagedEndpointCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateManagedEndpointCommandOutput) => void), cb?: (err: any, data?: CreateManagedEndpointCommandOutput) => void ): Promise<CreateManagedEndpointCommandOutput> | void { const command = new CreateManagedEndpointCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements.</p> */ public createVirtualCluster( args: CreateVirtualClusterCommandInput, options?: __HttpHandlerOptions ): Promise<CreateVirtualClusterCommandOutput>; public createVirtualCluster( args: CreateVirtualClusterCommandInput, cb: (err: any, data?: CreateVirtualClusterCommandOutput) => void ): void; public createVirtualCluster( args: CreateVirtualClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateVirtualClusterCommandOutput) => void ): void; public createVirtualCluster( args: CreateVirtualClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateVirtualClusterCommandOutput) => void), cb?: (err: any, data?: CreateVirtualClusterCommandOutput) => void ): Promise<CreateVirtualClusterCommandOutput> | void { const command = new CreateVirtualClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster.</p> */ public deleteManagedEndpoint( args: DeleteManagedEndpointCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteManagedEndpointCommandOutput>; public deleteManagedEndpoint( args: DeleteManagedEndpointCommandInput, cb: (err: any, data?: DeleteManagedEndpointCommandOutput) => void ): void; public deleteManagedEndpoint( args: DeleteManagedEndpointCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteManagedEndpointCommandOutput) => void ): void; public deleteManagedEndpoint( args: DeleteManagedEndpointCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteManagedEndpointCommandOutput) => void), cb?: (err: any, data?: DeleteManagedEndpointCommandOutput) => void ): Promise<DeleteManagedEndpointCommandOutput> | void { const command = new DeleteManagedEndpointCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements.</p> */ public deleteVirtualCluster( args: DeleteVirtualClusterCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteVirtualClusterCommandOutput>; public deleteVirtualCluster( args: DeleteVirtualClusterCommandInput, cb: (err: any, data?: DeleteVirtualClusterCommandOutput) => void ): void; public deleteVirtualCluster( args: DeleteVirtualClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteVirtualClusterCommandOutput) => void ): void; public deleteVirtualCluster( args: DeleteVirtualClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteVirtualClusterCommandOutput) => void), cb?: (err: any, data?: DeleteVirtualClusterCommandOutput) => void ): Promise<DeleteVirtualClusterCommandOutput> | void { const command = new DeleteVirtualClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Displays detailed information about a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS.</p> */ public describeJobRun( args: DescribeJobRunCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeJobRunCommandOutput>; public describeJobRun( args: DescribeJobRunCommandInput, cb: (err: any, data?: DescribeJobRunCommandOutput) => void ): void; public describeJobRun( args: DescribeJobRunCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeJobRunCommandOutput) => void ): void; public describeJobRun( args: DescribeJobRunCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeJobRunCommandOutput) => void), cb?: (err: any, data?: DescribeJobRunCommandOutput) => void ): Promise<DescribeJobRunCommandOutput> | void { const command = new DescribeJobRunCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Displays detailed information about a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster.</p> */ public describeManagedEndpoint( args: DescribeManagedEndpointCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeManagedEndpointCommandOutput>; public describeManagedEndpoint( args: DescribeManagedEndpointCommandInput, cb: (err: any, data?: DescribeManagedEndpointCommandOutput) => void ): void; public describeManagedEndpoint( args: DescribeManagedEndpointCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeManagedEndpointCommandOutput) => void ): void; public describeManagedEndpoint( args: DescribeManagedEndpointCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeManagedEndpointCommandOutput) => void), cb?: (err: any, data?: DescribeManagedEndpointCommandOutput) => void ): Promise<DescribeManagedEndpointCommandOutput> | void { const command = new DescribeManagedEndpointCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Displays detailed information about a specified virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements.</p> */ public describeVirtualCluster( args: DescribeVirtualClusterCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeVirtualClusterCommandOutput>; public describeVirtualCluster( args: DescribeVirtualClusterCommandInput, cb: (err: any, data?: DescribeVirtualClusterCommandOutput) => void ): void; public describeVirtualCluster( args: DescribeVirtualClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeVirtualClusterCommandOutput) => void ): void; public describeVirtualCluster( args: DescribeVirtualClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeVirtualClusterCommandOutput) => void), cb?: (err: any, data?: DescribeVirtualClusterCommandOutput) => void ): Promise<DescribeVirtualClusterCommandOutput> | void { const command = new DescribeVirtualClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists job runs based on a set of parameters. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS.</p> */ public listJobRuns(args: ListJobRunsCommandInput, options?: __HttpHandlerOptions): Promise<ListJobRunsCommandOutput>; public listJobRuns(args: ListJobRunsCommandInput, cb: (err: any, data?: ListJobRunsCommandOutput) => void): void; public listJobRuns( args: ListJobRunsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListJobRunsCommandOutput) => void ): void; public listJobRuns( args: ListJobRunsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListJobRunsCommandOutput) => void), cb?: (err: any, data?: ListJobRunsCommandOutput) => void ): Promise<ListJobRunsCommandOutput> | void { const command = new ListJobRunsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists managed endpoints based on a set of parameters. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster.</p> */ public listManagedEndpoints( args: ListManagedEndpointsCommandInput, options?: __HttpHandlerOptions ): Promise<ListManagedEndpointsCommandOutput>; public listManagedEndpoints( args: ListManagedEndpointsCommandInput, cb: (err: any, data?: ListManagedEndpointsCommandOutput) => void ): void; public listManagedEndpoints( args: ListManagedEndpointsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListManagedEndpointsCommandOutput) => void ): void; public listManagedEndpoints( args: ListManagedEndpointsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListManagedEndpointsCommandOutput) => void), cb?: (err: any, data?: ListManagedEndpointsCommandOutput) => void ): Promise<ListManagedEndpointsCommandOutput> | void { const command = new ListManagedEndpointsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the tags assigned to the resources.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists information about the specified virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements.</p> */ public listVirtualClusters( args: ListVirtualClustersCommandInput, options?: __HttpHandlerOptions ): Promise<ListVirtualClustersCommandOutput>; public listVirtualClusters( args: ListVirtualClustersCommandInput, cb: (err: any, data?: ListVirtualClustersCommandOutput) => void ): void; public listVirtualClusters( args: ListVirtualClustersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListVirtualClustersCommandOutput) => void ): void; public listVirtualClusters( args: ListVirtualClustersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListVirtualClustersCommandOutput) => void), cb?: (err: any, data?: ListVirtualClustersCommandOutput) => void ): Promise<ListVirtualClustersCommandOutput> | void { const command = new ListVirtualClustersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Starts a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS.</p> */ public startJobRun(args: StartJobRunCommandInput, options?: __HttpHandlerOptions): Promise<StartJobRunCommandOutput>; public startJobRun(args: StartJobRunCommandInput, cb: (err: any, data?: StartJobRunCommandOutput) => void): void; public startJobRun( args: StartJobRunCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: StartJobRunCommandOutput) => void ): void; public startJobRun( args: StartJobRunCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartJobRunCommandOutput) => void), cb?: (err: any, data?: StartJobRunCommandOutput) => void ): Promise<StartJobRunCommandOutput> | void { const command = new StartJobRunCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Assigns tags to resources. A tag is a label that you assign to an AWS resource. Each tag consists of a key and an optional value, both of which you define. Tags enable you to categorize your AWS resources by attributes such as purpose, owner, or environment. When you have many resources of the same type, you can quickly identify a specific resource based on the tags you've assigned to it. For example, you can define a set of tags for your Amazon EMR on EKS clusters to help you track each cluster's owner and stack level. We recommend that you devise a consistent set of tag keys for each resource type. You can then search and filter the resources based on the tags that you add.</p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes tags from resources.</p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import TypeDataGridProps, { TypeComputedProps, TypeRowReorderFn, TypeBuildColumnsProps, } from './TypeDataGridProps'; import { TypeComputedColumn, TypeColumn, TypeColumns } from './TypeColumn'; import { MutableRefObject, ReactNode, CSSProperties } from 'react'; export { TypeSortInfo, TypeSingleSortInfo } from './TypeSortInfo'; export { TypeGroupBy } from './TypeGroupBy'; export { TypeSize } from './TypeSize'; export { TypeDataSource } from './TypeDataSource'; export { TypeFilterValue, TypeSingleFilterValue, TypeFilterType, TypeFilterTypes, TypeFilterOperator, } from './TypeFilterValue'; export { TypeDataGridProps, TypeComputeTreeData, TypeComputeTreeDataParam, TypeRowDetailsInfo, TypeComputedProps, TypePivotUniqueValuesDescriptor, } from './TypeDataGridProps'; export { TypeRowSelection, TypeRowUnselected, TypeCellSelection, } from './TypeSelected'; export { TypeColumn, TypeColumnGroup, TypeComputedColumn, TypeComputedColumnsMap, TypeColumnWithId, IColumn, } from './TypeColumn'; export { TypeRowReorderFn }; export type TypePivotColumnSummaryReducer = { initialValue: any; reducer: (acc: any, currentValue: any, item: any) => any; complete?: (acc: any, arr: any[]) => any; }; export type TypeGroup = { name: string; header?: ReactNode; headerAlign: 'start' | 'end' | 'center' | 'left' | 'right'; }; export type TypePivotItem = | { name: 'string'; summaryReducer?: TypePivotColumnSummaryReducer; summaryColumn?: Partial<TypeColumn>; summaryGroup?: Partial<TypeGroup>; } | 'string'; export { TypePaginationProps } from './TypePaginationProps'; export type TypeStickyRows = { [key: number]: number } | null; export type TypeEditInfo = { rowIndex: number; columnIndex: number; rowId: string; columnId: string; value?: any; }; export type TypeWithId = { id: string; }; export type TypePivotSummaryShape = { [groupName: string]: { array: any[]; field: string; values: { [colId: string]: any }; pivotColumnSummary: { [colId: string]: any }; pivotSummary: TypePivotSummaryShape | null; }; }; export type TypeGroupDataItem = { __group: boolean; leaf: boolean; value: string; depth: number; keyPath: string[]; fieldPath: string[]; groupSummary: any; groupColumnSummary: { [colName: string]: any } | null; pivotSummary: TypePivotSummaryShape | null; index?: number; }; export type TypeRowProps = { rowIndex: number; remoteRowIndex?: number; realIndex?: number; groupProps?: any; data: any; empty?: boolean; columns?: TypeComputedColumn[]; dataSourceArray?: any[]; }; export type TypeCollapsedRows = { [key: string]: boolean; }; export type TypeExpandedRows = TypeCollapsedRows | true; export type TypeExpandedNodes = { [key: string]: boolean; }; export type TypeNodeCache = { [key: string]: any; }; export type TypeDataSourceCache = | { [key: string]: any; } | undefined; export type TypeNodeProps = { expanded: boolean; loading: boolean; depth: number; path: string; leafNode: boolean; asyncNode: boolean; childIndex: number; parentNodeId: string | number; groupSummary?: any; groupColumnSummary?: { [colName: string]: any } | null; }; export type TypeCellProps = { rowIndex: number; columnIndex: number; computedVisibleIndex?: number; data?: any; name?: string; header?: | ReactNode | string | (( celProps: TypeCellProps, { cellProps, column, contextMenu, }: { cellProps: TypeCellProps; column: TypeComputedColumn; contextMenu: any; } ) => ReactNode); }; export type TypeShowCellBorders = true | false | 'vertical' | 'horizontal'; export type TypeLockedRow = { position?: 'start' | 'end'; cellStyle?: | CSSProperties | (( data: { row: TypeFooterRow; rowIndex: number; rowPosition: 'start' | 'end'; column: TypeComputedColumn; columnIndex: number; }, computedProps: TypeComputedProps ) => CSSProperties); cellClassName?: | string | (( data: { row: TypeFooterRow; rowIndex: number; rowPosition: 'start' | 'end'; column: TypeComputedColumn; columnIndex: number; }, computedProps: TypeComputedProps ) => string); render?: | { [key: string]: ( { row, rowIndex, summary, render, rowPosition, column, columnIndex, }: { summary?: any; row: TypeFooterRow; rowIndex: number; render?: any; rowPosition: 'start' | 'end'; column: TypeComputedColumn; columnIndex: number; }, computedProps: TypeComputedProps ) => ReactNode; } | (( { row, rowIndex, rowPosition, column, columnIndex, summary, }: { summary?: any; row: TypeFooterRow; rowIndex: number; rowPosition: 'start' | 'end'; column: TypeComputedColumn; columnIndex: number; }, computedProps: TypeComputedProps ) => ReactNode) | { [key: string]: any }; renderLockedStart?: ( { columns, value, summary, }: { columns: TypeComputedColumn[]; value: ReactNode; summary: any; }, computedProps: TypeComputedProps ) => ReactNode; renderUnlocked?: ( { columns, value, summary, }: { summary: any; columns: TypeComputedColumn[]; value: ReactNode; }, computedProps: TypeComputedProps ) => ReactNode; renderLockedEnd?: ( { columns, value, summary, }: { summary: any; columns: TypeComputedColumn[]; value: ReactNode; }, computedProps: TypeComputedProps ) => ReactNode; colspan?: | { [key: string]: number } | (( { column, columnIndex, rowPosition, row, rowIndex, }: { column: TypeComputedColumn; columnIndex: number; rowPosition: 'start' | 'end'; row: TypeFooterRow; rowIndex: number; }, computedProps: TypeComputedProps ) => number | null); }; export type TypeFooterRow = { position?: 'end'; cellStyle?: | CSSProperties | (( data: { row: TypeFooterRow; rowIndex: number; column: TypeComputedColumn; columnIndex: number; }, computedProps: TypeComputedProps ) => CSSProperties); cellClassName?: | string | (( data: { row: TypeFooterRow; rowIndex: number; column: TypeComputedColumn; columnIndex: number; }, computedProps: TypeComputedProps ) => string); render?: | { [key: string]: ( { row, rowIndex, summary, render, column, columnIndex, }: { summary?: any; row: TypeFooterRow; rowIndex: number; render?: any; column: TypeComputedColumn; columnIndex: number; }, computedProps: TypeComputedProps ) => ReactNode; } | (( { row, rowIndex, column, columnIndex, summary, }: { summary?: any; row: TypeFooterRow; rowIndex: number; column: TypeComputedColumn; columnIndex: number; }, computedProps: TypeComputedProps ) => ReactNode) | { [key: string]: any }; renderLockedStart?: ( { columns, value, summary, }: { columns: TypeComputedColumn[]; value: ReactNode; summary: any; }, computedProps: TypeComputedProps ) => ReactNode; renderUnlocked?: ( { columns, value, summary, }: { summary: any; columns: TypeComputedColumn[]; value: ReactNode; }, computedProps: TypeComputedProps ) => ReactNode; renderLockedEnd?: ( { columns, value, summary, }: { summary: any; columns: TypeComputedColumn[]; value: ReactNode; }, computedProps: TypeComputedProps ) => ReactNode; colspan?: | { [key: string]: number } | (( { column, columnIndex, row, rowIndex, }: { column: TypeComputedColumn; columnIndex: number; row: TypeFooterRow; rowIndex: number; }, computedProps: TypeComputedProps ) => number | null); }; export interface TypeBatchUpdateQueue { (fn: () => void): void; commit: (extraFn?: () => void) => void; } export type TypeShowGroupSummaryRow = | 'start' | 'end' | boolean | ((group: TypeGroupDataItem) => 'start' | 'end' | boolean); export interface TypeSummaryReducer<T> { initialValue: T; reducer: (acc: T, currentValue: T, index: number, arr: any[]) => T; complete?: (acc: T, arr: any[]) => T; } export type TypeCollapsedGroups = true | { [key: string]: boolean }; export type TypeExpandedGroups = TypeCollapsedGroups; export type TypeGetColumnByParam = | string | number | TypeComputedColumn | { id: string | number; name?: string | number } | { name: string | number; id?: string | number }; export type TypePlugin = { name: string; hook: ( props: TypeDataGridProps, computedProps: TypeComputedProps, computedPropsRef: MutableRefObject<TypeComputedProps | null> ) => any; defaultProps?: (defaultProps: any) => any; maybeAddColumns?: ( columns: TypeColumns, props: TypeBuildColumnsProps ) => TypeColumns; }; export type TypeDetailsGridInfo = { __detailsPersisted?: boolean; masterDetailsInstances?: any; masterDetailsCache?: any; masterDetailsKeys?: any; unmountedDetails?: any; originalDetailsGrids?: any; }; export type TypeDragHelper = { onDrag: Function; onDrop: Function; }; export type TypeConstrainRegion = { 0: number; 1: number; bottom: number; left: number; right: number; top: number; _events: object; _eventsCount: number; _maxListeners: number; height: number; width: number; getHeight?: Function; }; export type TypeDiff = { top: number; left: number; }; export type TypeConfig = { diff: TypeDiff; didDrag: boolean; }; export type RangeResultType = { height: number; top: number; bottom: number; index: number; };
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { NodeModel } from '../../../src/diagram/objects/node-model'; import { Node } from '../../../src/diagram/objects/node'; import { TextElement } from '../../../src/diagram/core/elements/text-element'; import { ShapeAnnotationModel } from '../../../src'; import { getDiagramElement } from '../../../src/diagram/utility/dom-util'; import { MouseEvents } from '../interaction/mouseevents.spec'; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; /** * Annotation - changing offsets */ describe('Diagram Control', () => { describe('Annotations with zero offsets', () => { let diagram: Diagram; let ele: HTMLElement; let pathData: string = 'M540.3643,137.9336L546.7973,159.7016L570.3633,159.7296L550.7723,171.9366L558.9053,194.9966L540.3643,' + '179.4996L521.8223,194.9966L529.9553,171.9366L510.3633,159.7296L533.9313,159.7016L540.3643,137.9336z'; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram50' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Path', data: pathData }, annotations: [{ content: 'label data content for path node', height: 50, width: 50, offset: { x: 0, y: 0 }, style: { italic: true, whiteSpace: 'CollapseAll' } }] }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 300, offsetY: 100, shape: { type: 'Path', data: pathData }, annotations: [{ content: 'label data content for path node', height: 50, width: 50, offset: { x: 0, y: 0.5 }, style: { italic: true, whiteSpace: 'CollapseSpace' } }] }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 500, offsetY: 100, shape: { type: 'Path', data: pathData }, annotations: [{ content: 'label data content for path node', height: 50, width: 50, offset: { x: 0, y: 1 }, style: { italic: true, whiteSpace: 'PreserveAll' } }] }; diagram = new Diagram({ mode: 'SVG', width: 800, height: 800, nodes: [node, node2, node3] }); diagram.appendTo('#diagram50'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking annotation offsets as 0 in SVG rendering Mode', (done: Function) => { expect((diagram.nodes[0] as Node).wrapper.children[1].offsetX === 50 && (diagram.nodes[0] as Node).wrapper.children[1].offsetY === 50 && (diagram.nodes[1] as Node).wrapper.children[1].offsetX === 250 && (diagram.nodes[1] as Node).wrapper.children[1].offsetY === 100 && (diagram.nodes[2] as Node).wrapper.children[1].offsetX === 450 && (diagram.nodes[2] as Node).wrapper.children[1].offsetY === 150).toBe(true); done(); }); it('Checking annotation offset as 1 in SVG rendering Mode', (done: Function) => { (diagram.nodes[0] as NodeModel).annotations[0].offset.x = 1; (diagram.nodes[1] as NodeModel).annotations[0].offset.x = 1; (diagram.nodes[2] as NodeModel).annotations[0].offset.x = 1; diagram.dataBind(); expect((diagram.nodes[0] as Node).wrapper.children[1].offsetX === 150 && (diagram.nodes[0] as Node).wrapper.children[1].offsetY === 50 && (diagram.nodes[1] as Node).wrapper.children[1].offsetX === 350 && (diagram.nodes[1] as Node).wrapper.children[1].offsetY === 100 && (diagram.nodes[2] as Node).wrapper.children[1].offsetX === 550 && (diagram.nodes[2] as Node).wrapper.children[1].offsetY === 150).toBe(true); done(); }); }); describe('Annotations with zero offsets ', () => { let diagram: Diagram; let ele: HTMLElement; let pathData: string = 'M540.3643,137.9336L546.7973,159.7016L570.3633,159.7296L550.7723,171.9366L558.9053,194.9966L540.3643,' + '179.4996L521.8223,194.9966L529.9553,171.9366L510.3633,159.7296L533.9313,159.7016L540.3643,137.9336z'; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram50' }); document.body.appendChild(ele); let element1: TextElement = new TextElement(); element1.content = 'Text element with width/100 height/100'; element1.style.color = 'red'; element1.style.italic = true; element1.style.fontSize = 12; element1.offsetX = 400; element1.offsetY = 100; element1.style.fill = 'transparent'; element1.width = 100; element1.height = 100; element1.style.bold = true; element1.style.fontFamily = 'Arial'; element1.style.textAlign = 'Center'; let element2: TextElement = new TextElement(); element2.content = 'Text element without width and height'; element2.style.fontSize = 12; element2.style.fill = 'transparent'; element2.offsetX = 350; element2.offsetY = 250; element2.style.textAlign = 'Center'; element2.style.textWrapping = 'WrapWithOverflow'; let element3: TextElement = new TextElement(); element3.content = 'Text element align with left side'; element3.style.fill = 'transparent'; element3.style.fontSize = 12; element3.offsetX = 350; element3.offsetY = 400; element3.width = 100; element3.height = 100; element3.style.textAlign = 'Left'; element3.style.textWrapping = 'Wrap'; let element4: TextElement = new TextElement(); element4.content = 'Text element align with center'; element4.style.fontSize = 12; element4.style.fill = 'transparent'; element4.offsetX = 400; element4.offsetY = 550; element4.width = 100; element4.height = 100; element4.style.textAlign = 'Center'; element4.style.textWrapping = 'NoWrap'; let element5: TextElement = new TextElement(); element5.content = 'Text element align with right side'; element5.style.fontSize = 12; element5.style.fill = 'transparent'; element5.offsetX = 400; element5.offsetY = 700; element5.width = 100; element5.height = 100; element5.style.textAlign = 'Right'; let element6: TextElement = new TextElement(); element6.offsetX = 400; element6.offsetY = 700; element6.style.bold = true; element6.style.italic = true; diagram = new Diagram({ mode: 'SVG', width: '1000px', height: '1000px', basicElements: [element1, element2, element3, element4, element5, element6] }); diagram.appendTo('#diagram50'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking annotation offset as 1 in SVG rendering Mode', (done: Function) => { expect((diagram.basicElements[0] as TextElement).offsetX == 400 && (diagram.basicElements[0] as TextElement).offsetY == 100 && (diagram.basicElements[1] as TextElement).offsetX == 350 && (diagram.basicElements[1] as TextElement).offsetY == 250 && (diagram.basicElements[2] as TextElement).offsetX == 350 && (diagram.basicElements[2] as TextElement).offsetY == 400 && (diagram.basicElements[3] as TextElement).offsetX == 400 && (diagram.basicElements[3] as TextElement).offsetY == 550 ).toBe(true); done(); }); }); describe('Remove labels API ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram50' }); document.body.appendChild(ele); diagram = new Diagram({ mode: 'SVG', width: '1000px', height: '1000px', nodes: [ { id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 100, } ] }); diagram.appendTo('#diagram50'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking remove labels API', (done: Function) => { let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); let mouseEvents: MouseEvents = new MouseEvents(); let node: Node = diagram.nodes[0] as Node let label: ShapeAnnotationModel[] = [{ id: 'label1', content: 'Default Shape', offset: { x: 0 }, style: { color: 'rgb(255,250,235)' } }, { id: 'label2', content: 'Default Shape', offset: { y: 0 }, style: { color: '#000000' } }, { id: 'label3', content: 'Default Shape', offset: { x: 1 } }] diagram.addLabels(node, label); let label1 = document.getElementById('node1_label1_groupElement'); let label2 = document.getElementById('node1_label2_groupElement'); let label3 = document.getElementById('node1_label3_groupElement'); expect(label1 != null && label2 != null && label3 != null).toBe(true); diagram.removeLabels(node, node.annotations); label1 = document.getElementById('node1_label1_groupElement'); label2 = document.getElementById('node1_label2_groupElement'); label3 = document.getElementById('node1_label3_groupElement'); expect(label1.childNodes.length == 0 && label2.childNodes.length == 0 && label3.childNodes.length == 0).toBe(true); diagram.addLabels(node, label); diagram.startTextEdit(diagram.nodes[0], diagram.nodes[0].annotations[0].id); expect(document.getElementById('diagram50_editBox').style.background === 'black') mouseEvents.clickEvent(diagramCanvas, 10, 10); diagram.startTextEdit(diagram.nodes[0], diagram.nodes[0].annotations[1].id); expect(document.getElementById('diagram50_editBox').style.background === 'white') done(); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) }); });;
the_stack
import { Octokit } from '@octokit/rest'; import { GetResponseDataTypeFromEndpointMethod, GetResponseTypeFromEndpointMethod } from '@octokit/types'; import { isEqual } from 'lodash'; import { showWarningMessage } from '../../commons/utils/NotificationsHelper'; import { IMCQQuestion, Testcase } from '../assessment/AssessmentTypes'; import { MissionData, MissionMetadata, MissionRepoData, TaskData } from './GitHubMissionTypes'; export const maximumTasksPerMission = 20; const jsonStringify = (object: any) => JSON.stringify(object, null, 4); const convertTestsToSaveableJson = (tests: Testcase[]) => { const saveableTests = tests.map((test: Testcase) => { return { answer: test.answer, program: test.program, score: test.score ? test.score : 0, type: test.type ? test.type : 'public' }; }); return jsonStringify(saveableTests); }; const identity = (content: any) => content; // 1) fileName: the name of the file corresponding to the named property // 2) isDefaultValue: function should return true if the input value is the default value of the property // 3) fromStringConverter: a function to be applied to raw text data to convert it into the property // 4) toStringConverter: a function to be applied to the property to convert it to raw text data const taskDataPropertyTable = { taskDescription: { fileName: 'Problem.md', isDefaultValue: (value: string) => value === '', fromStringConverter: identity, toStringConverter: identity }, starterCode: { fileName: 'StarterCode.js', isDefaultValue: (value: string) => value === '', fromStringConverter: identity, toStringConverter: identity }, savedCode: { fileName: 'SavedCode.js', isDefaultValue: (value: string) => value === '', fromStringConverter: identity, toStringConverter: identity }, testPrepend: { fileName: 'TestPrepend.js', isDefaultValue: (value: string) => value === '', fromStringConverter: identity, toStringConverter: identity }, testPostpend: { fileName: 'TestPostpend.js', isDefaultValue: (value: string) => value === '', fromStringConverter: identity, toStringConverter: identity }, testCases: { fileName: 'TestCases.json', isDefaultValue: (value: Testcase[]) => value.length === 0, fromStringConverter: JSON.parse, toStringConverter: convertTestsToSaveableJson } }; /** * Retrieves mission information - such as the briefings, questions, metadata etc. from a GitHub Repository. * * @param missionRepoData Repository information where the mission is stored * @param octokit The Octokit instance for the authenticated user */ export async function getMissionData(missionRepoData: MissionRepoData, octokit: Octokit) { const briefingStringPromise = getContentAsString( missionRepoData.repoOwner, missionRepoData.repoName, 'README.md', octokit ); const metadataStringPromise = getContentAsString( missionRepoData.repoOwner, missionRepoData.repoName, '.metadata', octokit ); const tasksDataPromise = getTasksData( missionRepoData.repoOwner, missionRepoData.repoName, octokit ); const [briefingString, metadataString, tasksData] = await Promise.all([ briefingStringPromise, metadataStringPromise, tasksDataPromise ]); const missionMetadata = convertMetadataStringToMissionMetadata(metadataString); const newMissionData: MissionData = { missionRepoData: missionRepoData, missionBriefing: briefingString, missionMetadata: missionMetadata, tasksData: tasksData }; return newMissionData; } /** * Retrieves information regarding each task in the Mission from the GitHub repository. * * @param repoOwner The owner of the mission repository * @param repoName The name of the mission repository * @param octokit The Octokit instance for the authenticated user */ async function getTasksData(repoOwner: string, repoName: string, octokit: Octokit) { const questions: TaskData[] = []; if (octokit === undefined) { return questions; } // Get files in root type GetContentResponse = GetResponseTypeFromEndpointMethod<typeof octokit.repos.getContent>; const rootFolderContents: GetContentResponse = await octokit.repos.getContent({ owner: repoOwner, repo: repoName, path: '' }); type GetContentData = GetResponseDataTypeFromEndpointMethod<typeof octokit.repos.getContent>; const files: GetContentData = rootFolderContents.data; if (!Array.isArray(files)) { return questions; } const promises = []; for (let i = 1; i <= maximumTasksPerMission; i++) { const questionFolderName = 'Q' + i; // We make the assumption that there are no gaps in question numbering // If the question does not exist, we may break if (files.find(file => file.name === questionFolderName) === undefined) { break; } promises.push( octokit.repos .getContent({ owner: repoOwner, repo: repoName, path: questionFolderName }) .then((folderContents: GetContentResponse) => { if (!Array.isArray(folderContents.data)) { return; } const folderContentsAsArray = folderContents.data as any[]; const folderContentFileNames = folderContentsAsArray.map( (file: any) => file.name as string ); const properties = Object.keys(taskDataPropertyTable); const filteredProperties = properties.filter((property: string) => folderContentFileNames.includes(taskDataPropertyTable[property].fileName) ); const promises = filteredProperties.map(async (property: string) => { const fileName = taskDataPropertyTable[property].fileName; const stringContent = await getContentAsString( repoOwner, repoName, questionFolderName + '/' + fileName, octokit ); return taskDataPropertyTable[property].fromStringConverter(stringContent); }); return Promise.all(promises).then((stringContents: string[]) => { const taskData: TaskData = { questionNumber: i, taskDescription: '', starterCode: '', savedCode: '', testPrepend: '', testPostpend: '', testCases: [] }; for (let i = 0; i < stringContents.length; i++) { taskData[filteredProperties[i]] = stringContents[i]; } if (taskData.savedCode === '') { taskData.savedCode = taskData.starterCode; } questions.push(taskData); }); }) .catch(err => { showWarningMessage('Error occurred while trying to retrieve file content', 1000); console.error(err); }) ); } await Promise.all(promises); questions.sort((a, b) => a.questionNumber - b.questionNumber); return questions; } /** * Retrieves content from a single file on GitHub and returns it in string form. * * @param repoOwner The owner of the mission repository * @param repoName The name of the mission repository * @param filepath The path to the file to be retrieved * @param octokit The Octokit instance for the authenticated user */ export async function getContentAsString( repoOwner: string, repoName: string, filepath: string, octokit: Octokit ) { let contentString = ''; if (octokit === undefined) { return contentString; } try { type GetContentResponse = GetResponseTypeFromEndpointMethod<typeof octokit.repos.getContent>; const fileInfo: GetContentResponse = await octokit.repos.getContent({ owner: repoOwner, repo: repoName, path: filepath }); contentString = Buffer.from((fileInfo.data as any).content, 'base64').toString(); } catch (err) { showWarningMessage('Error occurred while trying to retrieve file content', 1000); console.error(err); } return contentString; } /** * Converts the contents of the '.metadata' file into a MissionMetadata object. * * @param metadataString The file contents of the '.metadata' file of a mission repository */ function convertMetadataStringToMissionMetadata(metadataString: string) { try { return JSON.parse(metadataString) as MissionMetadata; } catch (err) { console.error(err); return { sourceVersion: 4 } as MissionMetadata; } } function convertMissionMetadataToMetadataString(missionMetadata: MissionMetadata) { return jsonStringify(missionMetadata); } /** * Discovers files to be changed when saving to an existing GitHub repository * Return value is an array in the format [filenameToContentMap, foldersToDelete] * filenameToContentMap is an object whose key-value pairs are filenames and their new contents * foldersToDelete is an array containing the names of folders * @param missionMetadata The current MissionMetadata * @param cachedMissionMetadata The cached MissionMetadata * @param briefingContent The current briefing * @param cachedBriefingContent The cached briefing * @param taskList The current taskList * @param cachedTaskList The cached taskList * @param isTeacherMode If this is true, any changes to the saved code will be made to starter code instead */ export function discoverFilesToBeChangedWithMissionRepoData( missionMetadata: MissionMetadata, cachedMissionMetadata: MissionMetadata, briefingContent: string, cachedBriefingContent: string, taskList: TaskData[], cachedTaskList: TaskData[], isTeacherMode: boolean ): [any, string[]] { const filenameToContentMap = {}; const foldersToDelete: string[] = []; if (missionMetadata !== cachedMissionMetadata) { filenameToContentMap['.metadata'] = convertMissionMetadataToMetadataString(missionMetadata); } if (briefingContent !== cachedBriefingContent) { filenameToContentMap['README.md'] = briefingContent; } let i = 0; while (i < taskList.length) { const taskNumber = i + 1; const questionFolderName = 'Q' + taskNumber; if (taskNumber > cachedTaskList.length) { // Look for files to create filenameToContentMap[questionFolderName + '/StarterCode.js'] = taskList[i].savedCode; filenameToContentMap[questionFolderName + '/Problem.md'] = taskList[i].taskDescription; const propertiesToCheck = ['testCases', 'testPrepend', 'testPostpend']; for (const propertyName of propertiesToCheck) { const currentValue = taskList[i][propertyName]; const isDefaultValue = taskDataPropertyTable[propertyName].isDefaultValue(currentValue); if (!isDefaultValue) { const onRepoFileName = questionFolderName + '/' + taskDataPropertyTable[propertyName].fileName; const stringContent = taskDataPropertyTable[propertyName].toStringConverter( taskList[i][propertyName] ); filenameToContentMap[onRepoFileName] = stringContent; } } } else { // Look for files to edit const propertiesToCheck = Object.keys(taskDataPropertyTable); for (const propertyName of propertiesToCheck) { const currentValue = taskList[i][propertyName]; const cachedValue = cachedTaskList[i][propertyName]; if (!isEqual(currentValue, cachedValue)) { const onRepoFileName = questionFolderName + '/' + taskDataPropertyTable[propertyName].fileName; const stringContent = taskDataPropertyTable[propertyName].toStringConverter( taskList[i][propertyName] ); filenameToContentMap[onRepoFileName] = stringContent; } } if ( isTeacherMode && filenameToContentMap[questionFolderName + '/' + taskDataPropertyTable['savedCode'].fileName] ) { // replace changes to savedCode with changes to starterCode const savedCodeValue = filenameToContentMap[ questionFolderName + '/' + taskDataPropertyTable['savedCode'].fileName ]; delete filenameToContentMap[ questionFolderName + '/' + taskDataPropertyTable['savedCode'].fileName ]; filenameToContentMap[ questionFolderName + '/' + taskDataPropertyTable['starterCode'].fileName ] = savedCodeValue; } } i++; } while (i < cachedTaskList.length) { const taskNumber = i + 1; foldersToDelete.push('Q' + taskNumber); i++; } return [filenameToContentMap, foldersToDelete]; } /** * Discovers files to be changed when saving to a new GitHub repository * @param missionMetadata The current MissionMetadata * @param briefingContent The current briefing * @param taskList The current taskList */ export function discoverFilesToBeCreatedWithoutMissionRepoData( missionMetadata: MissionMetadata, briefingContent: string, taskList: TaskData[] ) { const filenameToContentMap = {}; filenameToContentMap['.metadata'] = convertMissionMetadataToMetadataString(missionMetadata); filenameToContentMap['README.md'] = briefingContent; const propertiesToCheck = ['testCases', 'testPrepend', 'testPostpend']; for (let i = 0; i < taskList.length; i++) { const taskNumber = i + 1; const questionFolderName = 'Q' + taskNumber; filenameToContentMap[questionFolderName + '/' + taskDataPropertyTable['starterCode'].fileName] = taskList[i].savedCode; filenameToContentMap[ questionFolderName + '/' + taskDataPropertyTable['taskDescription'].fileName ] = taskList[i].taskDescription; propertiesToCheck.forEach((propertyName: string) => { const currentValue = taskList[i][propertyName]; const isDefaultValue = taskDataPropertyTable[propertyName].isDefaultValue(currentValue); if (!isDefaultValue) { const onRepoFileName = questionFolderName + '/' + taskDataPropertyTable[propertyName].fileName; const stringContent = taskDataPropertyTable[propertyName].toStringConverter( taskList[i][propertyName] ); filenameToContentMap[onRepoFileName] = stringContent; } }); } return filenameToContentMap; } /** * Checks if the textual contents of a GitHub-hosted file is for an MCQ question, and converts it if so * returns an array of 2 values, a boolean and an IMCQQuestion * The boolean specifies whether the input corresponded to an MCQQuestion * The IMCQQuestion is only meaningful if the boolean is true, and contains the converted information * @param possibleMCQText The text to be checked and converted */ export function convertToMCQQuestionIfMCQText(possibleMCQText: string): [boolean, IMCQQuestion] { let isMCQText = false; const mcqQuestion = { answer: 0, choices: [], solution: -1, type: 'mcq', content: '', grade: 0, id: 0, library: { chapter: 4, external: { name: 'NONE', symbols: [] }, globals: [] }, maxGrade: 0, xp: 0, maxXp: 0 } as IMCQQuestion; const trimmedText = possibleMCQText.trim(); if (trimmedText.substring(0, 3).toLowerCase() === 'mcq') { isMCQText = true; } if (isMCQText) { const onlyQuestionInformation = trimmedText.substring(3, trimmedText.length); try { const intermediateObject = JSON.parse(onlyQuestionInformation); const studentAnswer = intermediateObject.answer; const intermediateChoices = intermediateObject.choices as any[]; const choices = intermediateChoices.map((question: { option: string; hint: string }) => { return { content: question.option, hint: question.hint }; }); const solution = intermediateObject.solution; mcqQuestion.answer = studentAnswer; mcqQuestion.choices = choices; mcqQuestion.solution = solution; } catch (err) { isMCQText = false; } } return [isMCQText, mcqQuestion]; } /** * Converts an IMCQQuestion object into textual contents to be saved to a GitHub repository * @param mcq The IMCQQuestion object */ export function convertIMCQQuestionToMCQText(mcq: IMCQQuestion) { const studentAnswer = mcq.answer; const choices = mcq.choices.map((choice: { content: string; hint: string | null }) => { return { option: choice.content, hint: choice.hint }; }); const solution = mcq.solution; const json = { choices: choices, answer: studentAnswer, solution: solution }; return 'MCQ\n' + jsonStringify(json); }
the_stack
import { addExpressionUI, cookieCleanup, updateSetting, } from '../redux/Actions'; import { clearCookiesForThisDomain, clearLocalStorageForThisDomain, clearSiteDataForThisDomain, } from './CleanupService'; import { cadLog, eventListenerActions, getHostname, getSetting, localFileToRegex, parseCookieStoreId, showNotification, siteDataToBrowser, SITEDATATYPES, } from './Libs'; import StoreUser from './StoreUser'; export default class ContextMenuEvents extends StoreUser { public static MenuID = { ACTIVE_MODE: 'cad-active-mode', CLEAN: 'cad-clean', CLEAN_OPEN: 'cad-clean-open', LINK_ADD_GREY_DOMAIN: 'cad-link-add-grey-domain', LINK_ADD_GREY_SUBS: 'cad-link-add-grey-subs', LINK_ADD_WHITE_DOMAIN: 'cad-link-add-white-domain', LINK_ADD_WHITE_SUBS: 'cad-link-add-white-subs', PAGE_ADD_GREY_DOMAIN: 'cad-page-add-grey-domain', PAGE_ADD_GREY_SUBS: 'cad-page-add-grey-subs', PAGE_ADD_WHITE_DOMAIN: 'cad-page-add-white-domain', PAGE_ADD_WHITE_SUBS: 'cad-page-add-white-subs', PARENT_CLEAN: 'cad-parent-clean', PARENT_EXPRESSION: 'cad-parent-expression', PARENT_LINK_DOMAIN: 'cad-parent-link-domain', PARENT_LINK_SUBS: 'cad-parent-link-subs', PARENT_PAGE_DOMAIN: 'cad-parent-page-domain', PARENT_PAGE_SUBS: 'cad-parent-page-subs', PARENT_SELECT_DOMAIN: 'cad-parent-select-domain', PARENT_SELECT_SUBS: 'cad-parent-select-subs', MANUAL_CLEAN_SITEDATA: 'cad-clean-sitedata-', SELECT_ADD_GREY_DOMAIN: 'cad-select-add-grey-domain', SELECT_ADD_GREY_SUBS: 'cad-select-add-grey-subs', SELECT_ADD_WHITE_DOMAIN: 'cad-select-add-white-domain', SELECT_ADD_WHITE_SUBS: 'cad-select-add-white-subs', SETTINGS: 'cad-settings', }; public static menuInit(): void { if (!browser.contextMenus) return; if ( !getSetting( StoreUser.store.getState(), SettingID.CONTEXT_MENUS, ) as boolean ) return; if (ContextMenuEvents.isInitialized) return; ContextMenuEvents.isInitialized = true; // Clean Option Group ContextMenuEvents.menuCreate({ id: ContextMenuEvents.MenuID.PARENT_CLEAN, title: browser.i18n.getMessage('contextMenusParentClean'), }); // Regular Clean (exclude open tabs) ContextMenuEvents.menuCreate({ id: ContextMenuEvents.MenuID.CLEAN, parentId: ContextMenuEvents.MenuID.PARENT_CLEAN, title: browser.i18n.getMessage('cleanText'), }); // Clean (include open tabs) ContextMenuEvents.menuCreate({ id: ContextMenuEvents.MenuID.CLEAN_OPEN, parentId: ContextMenuEvents.MenuID.PARENT_CLEAN, title: browser.i18n.getMessage('cleanIgnoringOpenTabsText'), }); // Separator ContextMenuEvents.menuCreate({ parentId: ContextMenuEvents.MenuID.PARENT_CLEAN, type: 'separator', }); // Cleanup Warning ContextMenuEvents.menuCreate({ enabled: false, parentId: ContextMenuEvents.MenuID.PARENT_CLEAN, title: browser.i18n.getMessage('cleanupActionsBypass'), }); // Clean all available site data for domain. // SiteDataType (declare enum via Global.d.ts) somehow doesn't exist through the browser... [...SITEDATATYPES, 'All', 'Cookies'].sort().forEach((sd) => { ContextMenuEvents.menuCreate({ id: `${ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA}${sd}`, parentId: ContextMenuEvents.MenuID.PARENT_CLEAN, title: browser.i18n.getMessage(`manualCleanSiteData${sd}`), }); }); // Separator ContextMenuEvents.menuCreate({ type: 'separator', }); // Add Expression Option Group - page ContextMenuEvents.menuCreate({ contexts: ['link', 'page', 'selection'], id: ContextMenuEvents.MenuID.PARENT_EXPRESSION, title: browser.i18n.getMessage('contextMenusParentExpression'), }); // Link Group ContextMenuEvents.menuCreate({ contexts: ['link'], id: ContextMenuEvents.MenuID.PARENT_LINK_DOMAIN, parentId: ContextMenuEvents.MenuID.PARENT_EXPRESSION, title: browser.i18n.getMessage('contextMenusSelectedDomainLink'), }); ContextMenuEvents.menuCreate({ contexts: ['link'], id: ContextMenuEvents.MenuID.LINK_ADD_GREY_DOMAIN, parentId: ContextMenuEvents.MenuID.PARENT_LINK_DOMAIN, title: browser.i18n.getMessage('toGreyListText'), }); ContextMenuEvents.menuCreate({ contexts: ['link'], id: ContextMenuEvents.MenuID.LINK_ADD_WHITE_DOMAIN, parentId: ContextMenuEvents.MenuID.PARENT_LINK_DOMAIN, title: browser.i18n.getMessage('toWhiteListText'), }); ContextMenuEvents.menuCreate({ contexts: ['link'], id: ContextMenuEvents.MenuID.PARENT_LINK_SUBS, parentId: ContextMenuEvents.MenuID.PARENT_EXPRESSION, title: browser.i18n.getMessage('contextMenusSelectedSubdomainLink'), }); ContextMenuEvents.menuCreate({ contexts: ['link'], id: ContextMenuEvents.MenuID.LINK_ADD_GREY_SUBS, parentId: ContextMenuEvents.MenuID.PARENT_LINK_SUBS, title: browser.i18n.getMessage('toGreyListText'), }); ContextMenuEvents.menuCreate({ contexts: ['link'], id: ContextMenuEvents.MenuID.LINK_ADD_WHITE_SUBS, parentId: ContextMenuEvents.MenuID.PARENT_LINK_SUBS, title: browser.i18n.getMessage('toWhiteListText'), }); // Page Group ContextMenuEvents.menuCreate({ contexts: ['page'], id: ContextMenuEvents.MenuID.PARENT_PAGE_DOMAIN, parentId: ContextMenuEvents.MenuID.PARENT_EXPRESSION, title: browser.i18n.getMessage('contextMenusSelectedDomainPage'), }); ContextMenuEvents.menuCreate({ contexts: ['page'], id: ContextMenuEvents.MenuID.PAGE_ADD_GREY_DOMAIN, parentId: ContextMenuEvents.MenuID.PARENT_PAGE_DOMAIN, title: browser.i18n.getMessage('toGreyListText'), }); ContextMenuEvents.menuCreate({ contexts: ['page'], id: ContextMenuEvents.MenuID.PAGE_ADD_WHITE_DOMAIN, parentId: ContextMenuEvents.MenuID.PARENT_PAGE_DOMAIN, title: browser.i18n.getMessage('toWhiteListText'), }); ContextMenuEvents.menuCreate({ contexts: ['page'], id: ContextMenuEvents.MenuID.PARENT_PAGE_SUBS, parentId: ContextMenuEvents.MenuID.PARENT_EXPRESSION, title: browser.i18n.getMessage('contextMenusSelectedSubdomainPage'), }); ContextMenuEvents.menuCreate({ contexts: ['page'], id: ContextMenuEvents.MenuID.PAGE_ADD_GREY_SUBS, parentId: ContextMenuEvents.MenuID.PARENT_PAGE_SUBS, title: browser.i18n.getMessage('toGreyListText'), }); ContextMenuEvents.menuCreate({ contexts: ['page'], id: ContextMenuEvents.MenuID.PAGE_ADD_WHITE_SUBS, parentId: ContextMenuEvents.MenuID.PARENT_PAGE_SUBS, title: browser.i18n.getMessage('toWhiteListText'), }); // Selection Group ContextMenuEvents.menuCreate({ contexts: ['selection'], id: ContextMenuEvents.MenuID.PARENT_SELECT_DOMAIN, parentId: ContextMenuEvents.MenuID.PARENT_EXPRESSION, title: browser.i18n.getMessage('contextMenusSelectedDomainText', ['%s']), }); ContextMenuEvents.menuCreate({ contexts: ['selection'], id: ContextMenuEvents.MenuID.SELECT_ADD_GREY_DOMAIN, parentId: ContextMenuEvents.MenuID.PARENT_SELECT_DOMAIN, title: browser.i18n.getMessage('toGreyListText'), }); ContextMenuEvents.menuCreate({ contexts: ['selection'], id: ContextMenuEvents.MenuID.SELECT_ADD_WHITE_DOMAIN, parentId: ContextMenuEvents.MenuID.PARENT_SELECT_DOMAIN, title: browser.i18n.getMessage('toWhiteListText'), }); ContextMenuEvents.menuCreate({ contexts: ['selection'], id: ContextMenuEvents.MenuID.PARENT_SELECT_SUBS, parentId: ContextMenuEvents.MenuID.PARENT_EXPRESSION, title: browser.i18n.getMessage('contextMenusSelectedSubdomainText', [ '%s', ]), }); ContextMenuEvents.menuCreate({ contexts: ['selection'], id: ContextMenuEvents.MenuID.SELECT_ADD_GREY_SUBS, parentId: ContextMenuEvents.MenuID.PARENT_SELECT_SUBS, title: browser.i18n.getMessage('toGreyListText'), }); ContextMenuEvents.menuCreate({ contexts: ['selection'], id: ContextMenuEvents.MenuID.SELECT_ADD_WHITE_SUBS, parentId: ContextMenuEvents.MenuID.PARENT_SELECT_SUBS, title: browser.i18n.getMessage('toWhiteListText'), }); // Separator ContextMenuEvents.menuCreate({ type: 'separator', }); // Active Mode ContextMenuEvents.menuCreate({ checked: getSetting( StoreUser.store.getState(), SettingID.ACTIVE_MODE, ) as boolean, id: ContextMenuEvents.MenuID.ACTIVE_MODE, title: browser.i18n.getMessage('activeModeText'), type: 'checkbox', }); // CAD Settings Page. Opens in a new tab next to the current one. ContextMenuEvents.menuCreate({ id: ContextMenuEvents.MenuID.SETTINGS, title: browser.i18n.getMessage('settingsText'), }); eventListenerActions( browser.contextMenus.onClicked, ContextMenuEvents.onContextMenuClicked, EventListenerAction.ADD, ); } public static async menuClear(): Promise<void> { await browser.contextMenus.removeAll(); eventListenerActions( browser.contextMenus.onClicked, ContextMenuEvents.onContextMenuClicked, EventListenerAction.REMOVE, ); ContextMenuEvents.isInitialized = false; cadLog( { msg: `ContextMenuEvents.menuClear: Context Menu has been removed.`, }, getSetting(StoreUser.store.getState(), SettingID.DEBUG_MODE) as boolean, ); } protected static menuCreate( createProperties: Parameters<typeof browser.contextMenus.create>[0], ): number | string { return browser.contextMenus.create( { ...createProperties, contexts: createProperties.contexts ? createProperties.contexts : ['browser_action', 'page'], }, ContextMenuEvents.onCreatedOrUpdated, ); } public static updateMenuItemCheckbox(id: string, checked: boolean): void { browser.contextMenus .update(id, { checked, }) .finally(this.onCreatedOrUpdated); cadLog( { msg: `ContextMenuEvents.updateMenuItemCheckbox: Updated Menu Item.`, x: { id, checked }, }, getSetting(StoreUser.store.getState(), SettingID.DEBUG_MODE) as boolean, ); } public static onCreatedOrUpdated(): void { const debug = getSetting( StoreUser.store.getState(), SettingID.DEBUG_MODE, ) as boolean; if (browser.runtime.lastError) { cadLog( { msg: `ContextMenuEvents.onCreatedOrUpdated received an error: ${browser.runtime.lastError}`, type: 'error', }, true, ); } else { cadLog( { msg: `ContextMenuEvents.onCreatedOrUpdated: Create/Update contextMenuItem was successful.`, }, debug, ); } } public static async onContextMenuClicked( info: browser.contextMenus.OnClickData, tab: browser.tabs.Tab, ): Promise<void> { const debug = getSetting( StoreUser.store.getState(), SettingID.DEBUG_MODE, ) as boolean; const contextualIdentities = getSetting( StoreUser.store.getState(), SettingID.CONTEXTUAL_IDENTITIES, ) as boolean; cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: Data received`, x: { info, tab }, }, debug, ); const cookieStoreId = (tab && tab.cookieStoreId) || ''; const selectionText = (info && info.selectionText) || ''; if ( info.menuItemId .toString() .startsWith(ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA) ) { const siteData = info.menuItemId .toString() .slice(ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA.length); const hostname = getHostname(tab.url); if (!hostname) { cadLog( { msg: `ContextMenuEvents.onContextMenuClicked cannot clean ${siteData} from tab:`, type: 'warn', x: { tab }, }, debug, ); showNotification({ duration: getSetting( StoreUser.store.getState(), SettingID.NOTIFY_DURATION, ) as number, msg: `${browser.i18n.getMessage('manualCleanError', [ browser.i18n.getMessage( `${siteDataToBrowser(siteData as SiteDataType)}Text`, ), ])}\n ${tab.title}\n\n ${tab.url} `, }); return; } cadLog( { msg: `ContextMenuEvents.onContextMenuClicked triggered Clean Site Data (${siteData}) For This Domain.`, }, debug, ); if (siteData === 'Cookies') { await clearCookiesForThisDomain(StoreUser.store.getState(), tab); return; } switch (siteData) { case 'All': case SiteDataType.CACHE: case SiteDataType.INDEXEDDB: case SiteDataType.PLUGINDATA: case SiteDataType.SERVICEWORKERS: await clearSiteDataForThisDomain( StoreUser.store.getState(), siteData, hostname, ); break; case SiteDataType.LOCALSTORAGE: await clearLocalStorageForThisDomain(StoreUser.store.getState(), tab); break; default: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked received unknown manual clean site data type: ${info.menuItemId}`, type: 'warn', x: { info, tab }, }, debug, ); break; } return; } switch (info.menuItemId) { case ContextMenuEvents.MenuID.CLEAN: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked triggered Normal Clean.`, }, debug, ); StoreUser.store.dispatch<any>( cookieCleanup({ greyCleanup: false, ignoreOpenTabs: false, }), ); break; case ContextMenuEvents.MenuID.CLEAN_OPEN: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked triggered Clean, include open tabs.`, }, debug, ); StoreUser.store.dispatch<any>( cookieCleanup({ greyCleanup: false, ignoreOpenTabs: true, }), ); break; case ContextMenuEvents.MenuID.LINK_ADD_GREY_DOMAIN: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was LINK_ADD_GREY_DOMAIN.`, x: { linkUrl: info.linkUrl, hostname: getHostname(info.linkUrl), cookieStoreId, }, }, debug, ); ContextMenuEvents.addNewExpression( getHostname(info.linkUrl), ListType.GREY, cookieStoreId, ); break; case ContextMenuEvents.MenuID.LINK_ADD_WHITE_DOMAIN: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was LINK_ADD_WHITE_DOMAIN.`, x: { linkUrl: info.linkUrl, hostname: getHostname(info.linkUrl), cookieStoreId, }, }, debug, ); ContextMenuEvents.addNewExpression( getHostname(info.linkUrl), ListType.WHITE, cookieStoreId, ); break; case ContextMenuEvents.MenuID.LINK_ADD_GREY_SUBS: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was LINK_ADD_GREY_SUBS.`, x: { linkUrl: info.linkUrl, hostname: getHostname(info.linkUrl), cookieStoreId, }, }, debug, ); ContextMenuEvents.addNewExpression( `*.${getHostname(info.linkUrl)}`, ListType.GREY, cookieStoreId, ); break; case ContextMenuEvents.MenuID.LINK_ADD_WHITE_SUBS: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was LINK_ADD_WHITE_SUBS.`, x: { linkUrl: info.linkUrl, hostname: getHostname(info.linkUrl), cookieStoreId, }, }, debug, ); ContextMenuEvents.addNewExpression( `*.${getHostname(info.linkUrl)}`, ListType.WHITE, cookieStoreId, ); break; case ContextMenuEvents.MenuID.PAGE_ADD_GREY_DOMAIN: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was PAGE_ADD_GREY_DOMAIN.`, x: { pageURL: info.pageUrl, hostname: getHostname(info.pageUrl), cookieStoreId, parsedCookieStoreId: parseCookieStoreId( contextualIdentities, cookieStoreId, ), }, }, debug, ); ContextMenuEvents.addNewExpression( getHostname(info.pageUrl), ListType.GREY, cookieStoreId, ); break; case ContextMenuEvents.MenuID.PAGE_ADD_WHITE_DOMAIN: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was PAGE_ADD_WHITE_DOMAIN.`, x: { pageURL: info.pageUrl, hostname: getHostname(info.pageUrl), cookieStoreId, parsedCookieStoreId: parseCookieStoreId( contextualIdentities, cookieStoreId, ), }, }, debug, ); ContextMenuEvents.addNewExpression( getHostname(info.pageUrl), ListType.WHITE, cookieStoreId, ); break; case ContextMenuEvents.MenuID.PAGE_ADD_GREY_SUBS: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was PAGE_ADD_GREY_SUBS.`, x: { pageURL: info.pageUrl, hostname: getHostname(info.pageUrl), cookieStoreId, parsedCookieStoreId: parseCookieStoreId( contextualIdentities, cookieStoreId, ), }, }, debug, ); ContextMenuEvents.addNewExpression( `*.${getHostname(info.pageUrl)}`, ListType.GREY, cookieStoreId, ); break; case ContextMenuEvents.MenuID.PAGE_ADD_WHITE_SUBS: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was PAGE_ADD_WHITE_SUBS.`, x: { pageURL: info.pageUrl, hostname: getHostname(info.pageUrl), cookieStoreId, parsedCookieStoreId: parseCookieStoreId( contextualIdentities, cookieStoreId, ), }, }, debug, ); ContextMenuEvents.addNewExpression( `*.${getHostname(info.pageUrl)}`, ListType.WHITE, cookieStoreId, ); break; case ContextMenuEvents.MenuID.SELECT_ADD_GREY_DOMAIN: { const texts = selectionText.trim().split(','); cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was SELECT_ADD_GREY_DOMAIN.`, x: { selectionText: info.selectionText, texts, cookieStoreId, parsedCookieStoreId: parseCookieStoreId( contextualIdentities, cookieStoreId, ), }, }, debug, ); texts.forEach((text) => { cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: encodeURI on selected text`, x: { rawInput: text.trim(), encodedInput: encodeURI(text.trim()), }, }, debug, ); ContextMenuEvents.addNewExpression( encodeURI(text.trim()), ListType.GREY, cookieStoreId, ); }); } break; case ContextMenuEvents.MenuID.SELECT_ADD_WHITE_DOMAIN: { const texts = selectionText.trim().split(','); cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was SELECT_ADD_WHITE_DOMAIN.`, x: { selectionText: info.selectionText, texts, cookieStoreId, parsedCookieStoreId: parseCookieStoreId( contextualIdentities, cookieStoreId, ), }, }, debug, ); texts.forEach((text) => { cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: encodeURI on selected text`, x: { rawInput: text.trim(), encodedInput: encodeURI(text.trim()), }, }, debug, ); ContextMenuEvents.addNewExpression( encodeURI(text.trim()), ListType.WHITE, cookieStoreId, ); }); } break; case ContextMenuEvents.MenuID.SELECT_ADD_GREY_SUBS: { const texts = selectionText.trim().split(','); cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was SELECT_ADD_GREY_SUBS.`, x: { selectionText: info.selectionText, texts, cookieStoreId, parsedCookieStoreId: parseCookieStoreId( contextualIdentities, cookieStoreId, ), }, }, debug, ); texts.forEach((text) => { cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: encodeURI on selected text`, x: { rawInput: text.trim(), encodedInput: encodeURI(text.trim()), }, }, debug, ); ContextMenuEvents.addNewExpression( `*.${encodeURI(text.trim())}`, ListType.GREY, cookieStoreId, ); }); } break; case ContextMenuEvents.MenuID.SELECT_ADD_WHITE_SUBS: { const texts = selectionText.trim().split(','); cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: menuItemId was SELECT_ADD_WHITE_SUBS.`, x: { selectionText: info.selectionText, texts, cookieStoreId, parsedCookieStoreId: parseCookieStoreId( contextualIdentities, cookieStoreId, ), }, }, debug, ); texts.forEach((text) => { cadLog( { msg: `ContextMenuEvents.onContextMenuClicked: encodeURI on selected text`, x: { rawInput: text.trim(), encodedInput: encodeURI(text.trim()), }, }, debug, ); ContextMenuEvents.addNewExpression( `*.${encodeURI(text.trim())}`, ListType.WHITE, cookieStoreId, ); }); } break; case ContextMenuEvents.MenuID.ACTIVE_MODE: if ( Object.prototype.hasOwnProperty.call(info, 'checked') && Object.prototype.hasOwnProperty.call(info, 'wasChecked') && info.checked !== info.wasChecked ) { cadLog( { msg: `ContextMenuEvents.onContextMenuClicked changed Automatic Cleaning value to: ${info.checked}.`, }, debug, ); // Setting Updated. StoreUser.store.dispatch<any>( updateSetting({ name: SettingID.ACTIVE_MODE, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion value: info.checked!, }), ); } break; case ContextMenuEvents.MenuID.SETTINGS: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked triggered Open Settings.`, }, debug, ); await browser.tabs.create({ index: tab.index + 1, url: '/settings/settings.html#tabSettings', }); break; default: cadLog( { msg: `ContextMenuEvents.onContextMenuClicked received unknown menu id: ${info.menuItemId}`, type: 'warn', x: { info, tab }, }, debug, ); break; } } protected static addNewExpression( input: string, listType: ListType, cookieStoreId: string | undefined, ): void { if (input.trim() === '' || input === '*.') { showNotification({ duration: getSetting( StoreUser.store.getState(), SettingID.NOTIFY_DURATION, ) as number, msg: `${browser.i18n.getMessage('addNewExpressionNotificationFailed')}`, }); return; } const payload = { expression: localFileToRegex(input.trim()), listType, storeId: parseCookieStoreId( getSetting( StoreUser.store.getState(), SettingID.CONTEXTUAL_IDENTITIES, ) as boolean, cookieStoreId, ), }; cadLog( { msg: `background.addNewExpression - Parsed from Right-Click:`, x: payload, }, getSetting(StoreUser.store.getState(), SettingID.DEBUG_MODE) as boolean, ); const cache = StoreUser.store.getState().cache; showNotification({ duration: getSetting( StoreUser.store.getState(), SettingID.NOTIFY_DURATION, ) as number, msg: `${browser.i18n.getMessage('addNewExpressionNotification', [ payload.expression, payload.listType, `${payload.storeId}${ (getSetting( StoreUser.store.getState(), SettingID.CONTEXTUAL_IDENTITIES, ) as boolean) ? cache[payload.storeId] !== undefined ? ` (${cache[payload.storeId]})` : '' : '' }`, ])}\n${browser.i18n.getMessage('addNewExpressionNotificationIgnore')}`, }); StoreUser.store.dispatch<any>(addExpressionUI(payload)); } protected static isInitialized = false; }
the_stack
import * as Json from "jsonc-parser" import { Segment } from "vscode-json-languageservice" import { YAMLDocument } from ".." import { CustomTag, JSONSchema } from "../../model" import * as objects from "../../utils" import localize from "./localize" import { ErrorCode, ProblemSeverity, ValidationResult } from "./validation-result" export interface IApplicableSchema { node: ASTNode inverted?: boolean schema: JSONSchema } export enum EnumMatch { Key, Enum } export interface ISchemaCollector { schemas: IApplicableSchema[] add(schema: IApplicableSchema): void merge(other: ISchemaCollector): void include(node: ASTNode): boolean newSub(): ISchemaCollector } // genericComparison tries to find the best matching schema using a generic comparison function genericComparison( maxOneMatch: boolean, subValidationResult: ValidationResult, bestMatch, subSchema, subMatchingSchemas ) { if ( !maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems() ) { // no errors, both are equally good matches bestMatch.matchingSchemas.merge(subMatchingSchemas) bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches } else { const compareResult = subValidationResult.compareGeneric( bestMatch.validationResult ) if (compareResult > 0) { // our node is the best matching so far bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas } } else if (compareResult === 0) { // there's already a best matching but we are as good bestMatch.matchingSchemas.merge(subMatchingSchemas) bestMatch.validationResult.mergeEnumValues(subValidationResult) } } return bestMatch } export class ASTNode<TValue = unknown> { start: number end: number type: string parent: ASTNode location: Json.Segment customTag: CustomTag document: YAMLDocument protected _value: TValue = null constructor( document: YAMLDocument, parent: ASTNode, type: string, location: Json.Segment, start: number, end?: number, customTag?: CustomTag ) { this.type = type this.location = location this.start = start this.end = end this.parent = parent this.customTag = customTag this.document = document } get value(): TValue { return this._value } set value(newValue: TValue) { this._value = newValue } get nodeType(): string { return this.customTag ? this.customTag.returnType || this.type : this.type } getPath(): Json.JSONPath { const path = this.parent ? this.parent.getPath() : [] if (this.location !== null) { path.push(this.location) } return path } getLocation(): Segment | null { return this.location } getChildNodes(): ASTNode[] { return [] } getLastChild(): ASTNode { return null } contains(offset: number, includeRightBound: boolean = false): boolean { return ( (offset >= this.start && offset < this.end) || (includeRightBound && offset === this.end) ) } toString(): string { return ( "type: " + this.type + " (" + this.start + "/" + this.end + ")" + (this.parent ? " parent: {" + this.parent.toString() + "}" : "") ) } visit(visitor: (node: ASTNode) => boolean): boolean { return visitor(this) } getNodeFromOffset(offset: number): ASTNode { const findNode = (node: ASTNode): ASTNode => { if (offset >= node.start && offset < node.end) { const children = node.getChildNodes() for ( let i = 0; i < children.length && children[i].start <= offset; i++ ) { const item = findNode(children[i]) if (item) { return item } } return node } return null } return findNode(this) } getNodeCollectorCount(): number { const collector = [] const findNode = (node: ASTNode): ASTNode => { const children = node.getChildNodes() children.forEach(child => { const item = findNode(child) if (item && item.type === "property") { collector.push(item) } }) return node } findNode(this) return collector.length } getNodeFromOffsetEndInclusive(offset: number): ASTNode { const collector = [] const findNode = (node: ASTNode): ASTNode => { if (offset >= node.start && offset <= node.end) { const children = node.getChildNodes() for ( let i = 0; i < children.length && children[i].start <= offset; i++ ) { const item = findNode(children[i]) if (item) { collector.push(item) } } return node } return null } const foundNode = findNode(this) let currMinDist = Number.MAX_VALUE let currMinNode = null collector.forEach(currNode => { const minDist = currNode.end - offset + (offset - currNode.start) if (minDist < currMinDist) { currMinNode = currNode currMinDist = minDist } }) return currMinNode || foundNode } validate( schema: JSONSchema, validationResult: ValidationResult, matchingSchemas: ISchemaCollector ): void { if (!matchingSchemas.include(this)) { return } if (this.nodeType === "any") { return } if (Array.isArray(schema.type)) { if ((schema.type as string[]).indexOf(this.nodeType) === -1) { validationResult.problems.push({ location: { start: this.start, end: this.end }, severity: ProblemSeverity.Warning, message: schema.errorMessage || localize( "typeArrayMismatchWarning", "Incorrect type. Expected one of {0}.", (schema.type as string[]).join(", ") ) }) } } else if (schema.type) { if (this.nodeType !== schema.type) { validationResult.problems.push({ location: { start: this.start, end: this.end }, severity: ProblemSeverity.Warning, message: schema.errorMessage || localize( "typeMismatchWarning", 'Incorrect type. Expected "{0}".', schema.type ) }) } } if (Array.isArray(schema.allOf)) { schema.allOf.forEach(subSchema => { this.validate(subSchema, validationResult, matchingSchemas) }) } if (schema.not) { const subValidationResult = new ValidationResult() const subMatchingSchemas = matchingSchemas.newSub() this.validate(schema.not, subValidationResult, subMatchingSchemas) if (!subValidationResult.hasProblems()) { validationResult.problems.push({ location: { start: this.start, end: this.end }, severity: ProblemSeverity.Warning, message: localize( "notSchemaWarning", "Matches a schema that is not allowed." ) }) } subMatchingSchemas.schemas.forEach(ms => { ms.inverted = !ms.inverted matchingSchemas.add(ms) }) } const testAlternatives = ( alternatives: JSONSchema[], maxOneMatch: boolean ) => { const matches = [] // remember the best match that is used for error messages let bestMatch: { schema: JSONSchema validationResult: ValidationResult matchingSchemas: ISchemaCollector } = null alternatives.forEach(subSchema => { const subValidationResult = new ValidationResult() const subMatchingSchemas = matchingSchemas.newSub() this.validate( subSchema, subValidationResult, subMatchingSchemas ) if (!subValidationResult.hasProblems()) { matches.push(subSchema) } if (!bestMatch) { bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas } } else { bestMatch = genericComparison( maxOneMatch, subValidationResult, bestMatch, subSchema, subMatchingSchemas ) } }) if (matches.length > 1 && maxOneMatch) { validationResult.problems.push({ location: { start: this.start, end: this.start + 1 }, severity: ProblemSeverity.Warning, message: localize( "oneOfWarning", "Matches multiple schemas when only one must validate." ) }) } if (bestMatch !== null) { validationResult.merge(bestMatch.validationResult) validationResult.propertiesMatches += bestMatch.validationResult.propertiesMatches validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches matchingSchemas.merge(bestMatch.matchingSchemas) } return matches.length } if (Array.isArray(schema.anyOf)) { testAlternatives(schema.anyOf, false) } if (Array.isArray(schema.oneOf)) { testAlternatives(schema.oneOf, true) } if (Array.isArray(schema.enum)) { const val = this.value let enumValueMatch = false for (const e of schema.enum) { if (objects.equals(val, e)) { enumValueMatch = true break } } validationResult.enumValues = schema.enum validationResult.enumValueMatch = enumValueMatch if (!enumValueMatch) { validationResult.problems.push({ location: { start: this.start, end: this.end }, severity: ProblemSeverity.Warning, code: ErrorCode.EnumValueMismatch, message: schema.errorMessage || localize( "enumWarning", "Value is not accepted. Valid values: {0}.", schema.enum.map(v => JSON.stringify(v)).join(", ") ) }) } } if (schema.deprecationMessage && this.parent) { validationResult.problems.push({ location: { start: this.parent.start, end: this.parent.end }, severity: ProblemSeverity.Warning, message: schema.deprecationMessage }) } matchingSchemas.add({ node: this, schema }) } get(path: Segment[]): ASTNode | null { let currentNode: ASTNode = this for (let segment of path) { const found = currentNode.getChildNodes().find(node => { if (node.location === null) { const { value } = node if ( value && value instanceof ASTNode && value.location === segment ) { currentNode = value return true } } else if (node.location === segment) { currentNode = node return true } return false }) if (!found) { return null } } return currentNode || null } }
the_stack
import * as React from 'react'; import * as ReactDom from 'react-dom'; import { IPropertyPaneField, PropertyPaneFieldType, IPropertyPaneCustomFieldProps } from '@microsoft/sp-webpart-base'; import PropertyFieldSliderRangeHost, { IPropertyFieldSliderRangeHostProps } from './PropertyFieldSliderRangeHost'; import { SPComponentLoader } from '@microsoft/sp-loader'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; /** * @interface * Public properties of the PropertyFieldSliderRange custom field * */ export interface IPropertyFieldSliderRangeProps { /** * @var * Property field label displayed on top */ label: string; /** * @var * Initial value */ initialValue?: string; /** * @var * Disables the slider if set to true. Default is false. */ disabled?: boolean; /** * @var * The minimum value of the slider. Default is 0. */ min?: number; /** * @var * The maximum value of the slider. Default is 100. */ max?: number; /** * @var * Default 1 - Determines the size or amount of each interval or step the * slider takes between the min and max. The full specified value range of the * slider (max - min) should be evenly divisible by the step. */ step?: number; /** * @var * Determines whether the slider handles move horizontally (min on left, * max on right) or vertically (min on bottom, max on top). * Possible values: "horizontal", "vertical". */ orientation?: string; /** * @var * Display the value on left & right of the slider or not */ showValue?: boolean; /** * @function * Defines a onPropertyChange function to raise when the selected Color changed. * Normally this function must be always defined with the 'this.onPropertyChange' * method of the web part object. */ onPropertyChange(propertyPath: string, oldValue: any, newValue: any): void; /** * @function * This API is called to render the web part. * Normally this function must be always defined with the 'this.render.bind(this)' * method of the web part object. */ render(): void; /** * This property is used to indicate the web part's PropertyPane interaction mode: Reactive or NonReactive. * The default behaviour is Reactive. */ disableReactivePropertyChanges?: boolean; /** * @var * Parent Web Part properties */ properties: any; /** * @var * An UNIQUE key indicates the identity of this control */ key?: string; /** * The method is used to get the validation error message and determine whether the input value is valid or not. * * When it returns string: * - If valid, it returns empty string. * - If invalid, it returns the error message string and the text field will * show a red border and show an error message below the text field. * * When it returns Promise<string>: * - The resolved value is display as error message. * - The rejected, the value is thrown away. * */ onGetErrorMessage?: (value: string) => string | Promise<string>; /** * Custom Field will start to validate after users stop typing for `deferredValidationTime` milliseconds. * Default value is 200. */ deferredValidationTime?: number; } /** * @interface * Private properties of the PropertyFieldSliderRange custom field. * We separate public & private properties to include onRender & onDispose method waited * by the PropertyFieldCustom, witout asking to the developer to add it when he's using * the PropertyFieldSliderRange. * */ export interface IPropertyFieldSliderRangePropsInternal extends IPropertyPaneCustomFieldProps { label: string; initialValue?: string; targetProperty: string; showValue?: boolean; guid: string; disabled?: boolean; min?: number; max?: number; step?: number; orientation?: string; onRender(elem: HTMLElement): void; onDispose(elem: HTMLElement): void; onPropertyChange(propertyPath: string, oldValue: any, newValue: any): void; render(): void; disableReactivePropertyChanges?: boolean; properties: any; onGetErrorMessage?: (value: string) => string | Promise<string>; deferredValidationTime?: number; } /** * @interface * Represents a PropertyFieldSliderRange object * */ class PropertyFieldSliderRangeBuilder implements IPropertyPaneField<IPropertyFieldSliderRangePropsInternal> { //Properties defined by IPropertyPaneField public type: PropertyPaneFieldType = PropertyPaneFieldType.Custom; public targetProperty: string; public properties: IPropertyFieldSliderRangePropsInternal; //Custom properties private label: string; private initialValue: string; private guid: string; private disabled: boolean; private min: number; private max: number; private step: number; private orientation: string; private showValue: boolean; private onPropertyChange: (propertyPath: string, oldValue: any, newValue: any) => void; private customProperties: any; private key: string; private onGetErrorMessage: (value: string) => string | Promise<string>; private deferredValidationTime: number = 200; private renderWebPart: () => void; private disableReactivePropertyChanges: boolean = false; private latestValidateValue: string; private async: Async; private delayedValidate: (value: string) => void; /** * @function * Ctor */ public constructor(_targetProperty: string, _properties: IPropertyFieldSliderRangePropsInternal) { this.render = this.render.bind(this); this.targetProperty = _properties.targetProperty; this.properties = _properties; this.label = _properties.label; this.initialValue = _properties.initialValue; this.disabled = _properties.disabled; this.min = _properties.min; this.max = _properties.max; this.step = _properties.step; this.showValue = _properties.showValue; this.orientation = _properties.orientation; this.guid = _properties.guid; this.properties.onDispose = this.dispose; this.properties.onRender = this.render; this.onPropertyChange = _properties.onPropertyChange; this.customProperties = _properties.properties; this.key = _properties.key; this.onGetErrorMessage = _properties.onGetErrorMessage; if (_properties.deferredValidationTime !== undefined) this.deferredValidationTime = _properties.deferredValidationTime; this.renderWebPart = _properties.render; if (_properties.disableReactivePropertyChanges !== undefined && _properties.disableReactivePropertyChanges != null) this.disableReactivePropertyChanges = _properties.disableReactivePropertyChanges; this.async = new Async(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.deferredValidationTime); SPComponentLoader.loadCss('//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css'); } /** * @function * Renders the ColorPicker field content */ private render(elem: HTMLElement): void { //Construct the JSX properties const element: React.ReactElement<IPropertyFieldSliderRangeHostProps> = React.createElement(PropertyFieldSliderRangeHost, { label: this.label, initialValue: this.initialValue, targetProperty: this.targetProperty, disabled: this.disabled, min: this.min, max: this.max, step: this.step, orientation: this.orientation, showValue: this.showValue, onDispose: this.dispose, onRender: this.render, onPropertyChange: this.onPropertyChange, guid: this.guid, properties: this.customProperties, key: this.key, onGetErrorMessage: this.onGetErrorMessage, deferredValidationTime: this.deferredValidationTime, render: this.renderWebPart, disableReactivePropertyChanges: this.disableReactivePropertyChanges }); //Calls the REACT content generator ReactDom.render(element, elem); var jQueryCdn = '//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'; var jQueryUICdn = '//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js'; SPComponentLoader.loadScript(jQueryCdn, { globalExportsName: '$' }).then(($: any): void => { SPComponentLoader.loadScript(jQueryUICdn, { globalExportsName: '$' }).then((jqueryui: any): void => { ($ as any)('#' + this.guid + '-slider').slider({ range: true, min: this.min != null ? this.min : 0, max: this.max != null ? this.max : 100, step: this.step != null ? this.step : 1, disabled: this.disabled != null ? this.disabled : false, orientation: this.orientation != null ? this.orientation : 'horizontal', values: (this.initialValue != null && this.initialValue != '' && this.initialValue.split(",").length == 2) ? [ Number(this.initialValue.split(",")[0]), Number(this.initialValue.split(",")[1]) ] : [this.min, this.max], slide: function( event, ui ) { var value: string = ui.values[ 0 ] + "," + ui.values[ 1]; this.delayedValidate(value); /*if (this.onPropertyChange && value != null) { this.customProperties[this.targetProperty] = value; this.onPropertyChange(this.targetProperty, this.initialValue, value); }*/ ($ as any)('#' + this.guid + '-min').html(ui.values[0]); ($ as any)('#' + this.guid + '-max').html(ui.values[1]); }.bind(this) }); }); }); } /** * @function * Validates the new custom field value */ private validate(value: string): void { if (this.onGetErrorMessage === null || this.onGetErrorMessage === undefined) { this.notifyAfterValidate(this.initialValue, value); return; } if (this.latestValidateValue === value) return; this.latestValidateValue = value; var result: string | PromiseLike<string> = this.onGetErrorMessage(value || ''); if (result !== undefined) { if (typeof result === 'string') { if (result === undefined || result === '') this.notifyAfterValidate(this.initialValue, value); ((document.getElementById(this.guid + '-errorMssg1')) as any).innerHTML = result; ((document.getElementById(this.guid + '-errorMssg2')) as any).innerHTML = result; } else { result.then((errorMessage: string) => { if (errorMessage === undefined || errorMessage === '') this.notifyAfterValidate(this.initialValue, value); ((document.getElementById(this.guid + '-errorMssg1')) as any).innerHTML = errorMessage; ((document.getElementById(this.guid + '-errorMssg2')) as any).innerHTML = errorMessage; }); } } else { this.notifyAfterValidate(this.initialValue, value); } } /** * @function * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(oldValue: string, newValue: string) { if (this.onPropertyChange && newValue != null) { this.customProperties[this.targetProperty] = newValue; this.onPropertyChange(this.targetProperty, this.properties.initialValue, newValue); if (!this.disableReactivePropertyChanges && this.renderWebPart != null) this.renderWebPart(); } } /** * @function * Disposes the current object */ private dispose(elem: HTMLElement): void { if (this.async !== undefined) this.async.dispose(); } } function s4(): string { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } function getGuid(): string { return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } /** * @function * Helper method to create the customer field on the PropertyPane. * @param targetProperty - Target property the custom field is associated to. * @param properties - Strongly typed custom field properties. */ export function PropertyFieldSliderRange(targetProperty: string, properties: IPropertyFieldSliderRangeProps): IPropertyPaneField<IPropertyFieldSliderRangePropsInternal> { //Create an internal properties object from the given properties var newProperties: IPropertyFieldSliderRangePropsInternal = { label: properties.label, targetProperty: targetProperty, initialValue: properties.initialValue, disabled: properties.disabled, min: properties.min, max: properties.max, step: properties.step, showValue: properties.showValue, orientation: properties.orientation, guid: getGuid(), onPropertyChange: properties.onPropertyChange, properties: properties.properties, onDispose: null, onRender: null, key: properties.key, onGetErrorMessage: properties.onGetErrorMessage, deferredValidationTime: properties.deferredValidationTime, render: properties.render, disableReactivePropertyChanges: properties.disableReactivePropertyChanges }; //Calls the PropertyFieldSliderRange builder object //This object will simulate a PropertyFieldCustom to manage his rendering process return new PropertyFieldSliderRangeBuilder(targetProperty, newProperties); }
the_stack
import * as PTM from "./ASTTest"; // PTM = "Published Types and Methods", but this file can also include app-state and app-event handlers import Ambrosia = require("ambrosia-node"); import Utils = Ambrosia.Utils; import IC = Ambrosia.IC; import Messages = Ambrosia.Messages; import Meta = Ambrosia.Meta; import Streams = Ambrosia.Streams; // TODO: It's recommended that you move this namespace to your input file (./ASTTest.ts) then re-run code-gen export namespace State { export class AppState extends Ambrosia.AmbrosiaAppState { // TODO: Define your application state here /** * @param restoredAppState Supplied only when loading (restoring) a checkpoint, or (for a "VNext" AppState) when upgrading from the prior AppState.\ * **WARNING:** When loading a checkpoint, restoredAppState will be an object literal, so you must use this to reinstantiate any members that are (or contain) class references. */ constructor(restoredAppState?: AppState) { super(restoredAppState); if (restoredAppState) { // TODO: Re-initialize your application state from restoredAppState here // WARNING: You MUST reinstantiate all members that are (or contain) class references because restoredAppState is data-only } else { // TODO: Initialize your application state here } } } /** * Only assign this using the return value of IC.start(), the return value of the upgrade() method of your AmbrosiaAppState * instance, and [if not using the generated checkpointConsumer()] in the 'onFinished' callback of an IncomingCheckpoint object. */ export let _appState: AppState; } /** Returns an OutgoingCheckpoint object used to serialize app state to a checkpoint. */ export function checkpointProducer(): Streams.OutgoingCheckpoint { function onCheckpointSent(error?: Error): void { Utils.log(`checkpointProducer: ${error ? `Failed (reason: ${error.message})` : "Checkpoint saved"}`) } return (Streams.simpleCheckpointProducer(State._appState, onCheckpointSent)); } /** Returns an IncomingCheckpoint object used to receive a checkpoint of app state. */ export function checkpointConsumer(): Streams.IncomingCheckpoint { function onCheckpointReceived(appState?: Ambrosia.AmbrosiaAppState, error?: Error): void { if (!error) { if (!appState) // Should never happen { throw new Error(`An appState object was expected, not ${appState}`); } State._appState = appState as State.AppState; } Utils.log(`checkpointConsumer: ${error ? `Failed (reason: ${error.message})` : "Checkpoint loaded"}`); } return (Streams.simpleCheckpointConsumer<State.AppState>(State.AppState, onCheckpointReceived)); } /** This method responds to incoming Ambrosia messages (RPCs and AppEvents). */ export function messageDispatcher(message: Messages.DispatchedMessage): void { // WARNING! Rules for Message Handling: // // Rule 1: Messages must be handled - to completion - in the order received. For application (RPC) messages only, if there are messages that are known to // be commutative then this rule can be relaxed. // Reason: Using Ambrosia requires applications to have deterministic execution. Further, system messages (like TakeCheckpoint) from the IC rely on being // handled in the order they are sent to the app. This means being extremely careful about using non-synchronous code (like awaitable operations // or callbacks) inside message handlers: the safest path is to always only use synchronous code. // // Rule 2: Before a TakeCheckpoint message can be handled, all handlers for previously received messages must have completed (ie. finished executing). // If Rule #1 is followed, the app is automatically in compliance with Rule #2. // Reason: Unless your application has a way to capture (and rehydrate) runtime execution state (specifically the message handler stack) in the serialized // application state (checkpoint), recovery of the checkpoint will not be able to complete the in-flight message handlers. But if there are no // in-flight handlers at the time the checkpoint is taken (because they all completed), then the problem of how to complete them during recovery is moot. // // Rule 3: Avoid sending too many messages in a single message handler. // Reason: Because a message handler always has to run to completion (see Rule #1), if it runs for too long it can monopolize the system leading to performance issues. // Further, this becomes a very costly message to have to replay during recovery. So instead, when an message handler needs to send a large sequence (series) // of independent messages, it should be designed to be restartable so that the sequence can pick up where it left off (rather than starting over) when resuming // execution (ie. after loading a checkpoint that occurred during the long-running - but incomplete - sequence). Restartability is achieved by sending a // application-defined 'sequence continuation' message at the end of each batch, which describes the remaining work to be done. Because the handler for the // 'sequence continuation' message only ever sends the next batch plus the 'sequence continuation' message, it can run to completion quickly, which both keeps // the system responsive (by allowing interleaving I/O) while also complying with Rule #1. // In addition to this "continuation message" technique for sending a series, if any single message handler has to send a large number of messages it should be // sent in batches using either explicit batches (IC.queueFork + IC.flushQueue) or implicit batches (IC.callFork / IC.postFork) inside a setImmediate() callback. // This asynchrony is necessary to allow I/O with the IC to interleave, and is one of the few allowable exceptions to the "always only use asynchronous code" // dictate in Rule #1. Interleaving I/O allows the instance to service self-calls, and allows checkpoints to be taken between batches. dispatcher(message); } /** * Synchronous Ambrosia message dispatcher. * * **WARNING:** Avoid using any asynchronous features (async/await, promises, callbacks, timers, events, etc.). See "Rules for Message Handling" above. */ function dispatcher(message: Messages.DispatchedMessage): void { const loggingPrefix: string = "Dispatcher"; try { switch (message.type) { case Messages.DispatchedMessageType.RPC: let rpc: Messages.IncomingRPC = message as Messages.IncomingRPC; switch (rpc.methodID) { case IC.POST_METHOD_ID: try { let methodName: string = IC.getPostMethodName(rpc); let methodVersion: number = IC.getPostMethodVersion(rpc); // Use this to do version-specific method behavior switch (methodName) { case "makeName": { const firstName: string = IC.getPostMethodArg(rpc, "firstName?"); const lastName: string = IC.getPostMethodArg(rpc, "lastName?"); IC.postResult<PTM.Test.Names>(rpc, PTM.Test.makeName(firstName, lastName)); } break; default: { let errorMsg: string = `Post method '${methodName}' is not implemented`; Utils.log(`(${errorMsg})`, loggingPrefix) IC.postError(rpc, new Error(errorMsg)); } break; } } catch (error: unknown) { const err: Error = Utils.makeError(error); Utils.log(err); IC.postError(rpc, err); } break; case 123: { const p1: PTM.Test.Name[][] = rpc.getJsonParam("p1"); PTM.Test.DoIt(p1); } break; default: Utils.log(`Error: Method dispatch failed (reason: No method is associated with methodID ${rpc.methodID})`); break; } break; case Messages.DispatchedMessageType.AppEvent: let appEvent: Messages.AppEvent = message as Messages.AppEvent; switch (appEvent.eventType) { case Messages.AppEventType.ICStarting: // TODO: Add an exported [non-async] function 'onICStarting(): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.ICStarted: // TODO: Add an exported [non-async] function 'onICStarted(): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.ICConnected: // Note: Types and methods are published in this handler so that they're available regardless of the 'icHostingMode' Meta.publishType("MixedTest", "{ p1: string[], p2: string[][], p3: { p4: number, p5: string }[] }"); Meta.publishType("Name", "{ first: string, last: string }"); Meta.publishType("Names", "Name[]"); Meta.publishType("Nested", "{ abc: { a: Uint8Array, b: { c: Names } } }"); Meta.publishType("Letters", "number"); Meta.publishPostMethod("makeName", 1, ["firstName?: string", "lastName?: string"], "Names"); Meta.publishMethod(123, "DoIt", ["p1: Name[][]"]); // TODO: Add an exported [non-async] function 'onICConnected(): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.ICStopped: // TODO: Add an exported [non-async] function 'onICStopped(exitCode: number): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.ICReadyForSelfCallRpc: // TODO: Add an exported [non-async] function 'onICReadyForSelfCallRpc(): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.RecoveryComplete: // TODO: Add an exported [non-async] function 'onRecoveryComplete(): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.UpgradeState: // TODO: Add an exported [non-async] function 'onUpgradeState(upgradeMode: Messages.AppUpgradeMode): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here // Note: You will need to import Ambrosia to ./test/ASTTest.ts in order to reference the 'Messages' namespace. // Upgrading is performed by calling _appState.upgrade(), for example: // _appState = _appState.upgrade<AppStateVNext>(AppStateVNext); break; case Messages.AppEventType.UpgradeCode: // TODO: Add an exported [non-async] function 'onUpgradeCode(upgradeMode: Messages.AppUpgradeMode): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here // Note: You will need to import Ambrosia to ./test/ASTTest.ts in order to reference the 'Messages' namespace. // Upgrading is performed by calling IC.upgrade(), passing the new handlers from the "upgraded" PublisherFramework.g.ts, // which should be part of your app (alongside your original PublisherFramework.g.ts). break; case Messages.AppEventType.IncomingCheckpointStreamSize: // TODO: Add an exported [non-async] function 'onIncomingCheckpointStreamSize(): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.FirstStart: // TODO: Add an exported [non-async] function 'onFirstStart(): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.BecomingPrimary: // TODO: Add an exported [non-async] function 'onBecomingPrimary(): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.CheckpointLoaded: // TODO: Add an exported [non-async] function 'onCheckpointLoaded(checkpointSizeInBytes: number): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.CheckpointSaved: // TODO: Add an exported [non-async] function 'onCheckpointSaved(): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.UpgradeComplete: // TODO: Add an exported [non-async] function 'onUpgradeComplete(): void' to ./ASTTest.ts, then (after the next code-gen) a call to it will be generated here break; } break; } } catch (error: unknown) { let messageName: string = (message.type === Messages.DispatchedMessageType.AppEvent) ? `AppEvent:${Messages.AppEventType[(message as Messages.AppEvent).eventType]}` : Messages.DispatchedMessageType[message.type]; Utils.log(`Error: Failed to process ${messageName} message`); Utils.log(Utils.makeError(error)); } }
the_stack
import React from 'react'; import 'jest-styled-components'; import 'jest-axe/extend-expect'; import 'regenerator-runtime/runtime'; import { axe } from 'jest-axe'; import { fireEvent, render, act } from '@testing-library/react'; import { FormNextLink, FormPreviousLink } from 'grommet-icons'; import { Box, Button, Calendar, Grommet, Text, CalendarProps } from '../..'; const DATE = '2020-01-15T00:00:00-08:00'; const DATES = [ '2020-01-12T00:00:00-08:00', ['2020-01-08T00:00:00-08:00', '2020-01-10T00:00:00-08:00'], ]; describe('Calendar', () => { test('Calendar should have no accessibility violations', async () => { const { container } = render( <Grommet> <Calendar date={DATE} animate={false} /> </Grommet>, ); const results = await axe(container); expect(results).toHaveNoViolations(); }); test('date', () => { // need to set the date to avoid snapshot drift over time const { container } = render( <Grommet> <Calendar date={DATE} animate={false} /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); }); test('disabled', () => { // need to set the date to avoid snapshot drift over time // have disabled date be distinct from selected date const normalizeForTimezone = (value: string, timestamp: string) => { const hourDelta = parseInt(timestamp?.split(':')[0], 10); const valueOffset = hourDelta * 60 * 1000; // ms const localOffset = new Date().getTimezoneOffset() * 60 * 1000; return ( value && new Date( new Date(value).getTime() - valueOffset + localOffset, ).toISOString() ); }; const adjustedDate = normalizeForTimezone(DATE, '08:00:00.000Z'); const disabledDate = new Date(adjustedDate); disabledDate.setDate(disabledDate.getDate() + 1); const { asFragment } = render( <Grommet> <Calendar date={DATE} disabled={[disabledDate.toDateString()]} /> </Grommet>, ); expect(asFragment()).toMatchSnapshot(); }); test('dates', () => { const { container } = render( <Grommet> <Calendar dates={DATES} animate={false} /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); }); test('daysOfWeek', () => { const { container } = render( <Grommet> <Calendar daysOfWeek dates={DATES} animate={false} /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); }); test('size', () => { const { container } = render( <Grommet> <Calendar size="small" date={DATE} animate={false} /> <Calendar size="medium" date={DATE} animate={false} /> <Calendar size="large" date={DATE} animate={false} /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); }); test('fill', () => { const { container } = render( <Grommet> <Calendar fill date={DATE} animate={false} /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); }); test('firstDayOfWeek', () => { const { container } = render( <Grommet> <Calendar firstDayOfWeek={0} date={DATE} animate={false} /> <Calendar firstDayOfWeek={1} date={DATE} animate={false} /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); }); test('reference', () => { const { container } = render( <Grommet> <Calendar reference={DATE} animate={false} /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); }); test('showAdjacentDays', () => { const { container } = render( <Grommet> <Calendar date={DATE} animate={false} /> <Calendar date={DATE} animate={false} showAdjacentDays={false} /> <Calendar date={DATE} animate={false} showAdjacentDays="trim" /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); }); test('header', () => { const { container } = render( <Grommet> <Calendar date={DATE} onSelect={() => {}} size="small" bounds={['2020-09-08', '2020-12-13']} header={({ date, locale, onPreviousMonth, onNextMonth, previousInBound, nextInBound, }) => ( <Box direction="row" align="center" justify="between"> <Button onClick={previousInBound ? onPreviousMonth : undefined}> <Box> <FormPreviousLink /> </Box> </Button> <Text size="small"> <strong> {date.toLocaleDateString(locale, { month: 'long', year: 'numeric', })} </strong> </Text> <Button onClick={nextInBound ? onNextMonth : undefined}> <Box> <FormNextLink /> </Box> </Button> </Box> )} animate={false} /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); }); test('children', () => { const { container } = render( <Grommet> <Calendar date={DATE} fill animate={false}> {({ day }) => <Box>{day}</Box>} </Calendar> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); }); test('select date', () => { const onSelect = jest.fn(); const { getByText, container } = render( <Grommet> <Calendar date={DATE} onSelect={onSelect} animate={false} /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); fireEvent.click(getByText('17')); expect(onSelect).toBeCalledWith(expect.stringMatching(/^2020-01-17T/)); expect(container.firstChild).toMatchSnapshot(); }); test('select dates', () => { const onSelect = jest.fn(); const { getByText, container } = render( <Grommet> <Calendar dates={DATES} onSelect={onSelect} animate={false} /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); fireEvent.click(getByText('17')); expect(onSelect).toBeCalledWith(expect.stringMatching(/^2020-01-17T/)); expect(container.firstChild).toMatchSnapshot(); }); test('first day sunday week monday', () => { // When the first day of the month is Sunday, // and the request of firstDayOfWeek // is Monday, we are verifying we are not missing a week, issue 3253. const { container } = render( <Grommet> <Calendar firstDayOfWeek={1} date="2020-03-01T00:00:00-08:00" animate={false} /> </Grommet>, ); expect(container.firstChild).toMatchSnapshot(); }); test('change months', () => { jest.useFakeTimers('modern'); const { container, getByLabelText } = render( <Grommet> <Calendar date={DATE} /> </Grommet>, ); // Change the Calendar from January to December fireEvent.click(getByLabelText('Go to December 2019')); act(() => { jest.runAllTimers(); }); expect(container.firstChild).toMatchSnapshot(); // Change the Calendar back to January fireEvent.click(getByLabelText('Go to January 2020')); act(() => { jest.runAllTimers(); }); expect(container.firstChild).toMatchSnapshot(); }); test('select date with range', () => { const onSelect = jest.fn(); const { getByText } = render( <Grommet> <Calendar date={DATE} onSelect={onSelect} range animate={false} /> </Grommet>, ); // expect to be selecting end date of range, because date serves // as start. since selected date is < date we should set it as start fireEvent.click(getByText('11')); expect(onSelect).toBeCalledWith(expect.stringMatching(/2020-01-11T/)); fireEvent.click(getByText('20')); expect(onSelect).toBeCalledWith([ [ expect.stringMatching(/^2020-01-11T/), expect.stringMatching(/^2020-01-20T/), ], ]); }); test('select date with range no date set', () => { const onSelect = jest.fn(); const { getByText } = render( <Grommet> <Calendar reference="2020-07-01T00:00:00-08:00" onSelect={onSelect} range animate={false} /> </Grommet>, ); fireEvent.click(getByText('17')); fireEvent.click(getByText('20')); expect(onSelect).toBeCalledWith([ [ expect.stringMatching(/^2020-07-17T/), expect.stringMatching(/^2020-07-20T/), ], ]); }); test('select date greater and less than', () => { const onSelect = jest.fn(); const { getByLabelText } = render( <Grommet> <Calendar dates={[['2020-01-01T00:00:00-08:00', '2020-01-05T00:00:00-08:00']]} onSelect={onSelect} range animate={false} /> </Grommet>, ); // select date greater than January 1st fireEvent.click(getByLabelText('Fri Jan 03 2020')); expect(onSelect).toBeCalledWith([ [ expect.stringMatching(/^2020-01-03T/), expect.stringMatching(/^2020-01-05T/), ], ]); // select date less than January 3rd // activeDate is end, since this is before the start // date we should update the date fireEvent.click(getByLabelText('Wed Jan 01 2020')); expect(onSelect).toBeCalledWith(expect.stringMatching(/2020-01-01T/)); }); test('select date with same start date', () => { const onSelect = jest.fn(); const { getByLabelText } = render( <Grommet> <Calendar dates={[['2020-01-01T00:00:00-08:00', '2020-01-03T00:00:00-08:00']]} onSelect={onSelect} range animate={false} /> </Grommet>, ); // selecting same starting day fireEvent.click(getByLabelText('Wed Jan 01 2020')); expect(onSelect).toBeCalledWith(expect.stringMatching(/^2020-01-03T/)); }); test('select date with same date twice', () => { const onSelect = jest.fn(); const { getByLabelText } = render( <Grommet> <Calendar reference="2020-01-01T00:00:00-08:00" onSelect={onSelect} range animate={false} /> </Grommet>, ); fireEvent.click(getByLabelText('Fri Jan 03 2020')); expect(onSelect).toBeCalledWith(expect.stringMatching(/^2020-01-03T/)); fireEvent.click(getByLabelText('Fri Jan 03 2020')); expect(onSelect).toBeCalledWith(undefined); }); test('select date with same end date', () => { const onSelect = jest.fn(); const { getByLabelText } = render( <Grommet> <Calendar dates={[['2020-01-01T00:00:00-08:00', '2020-01-03T00:00:00-08:00']]} onSelect={onSelect} range animate={false} /> </Grommet>, ); // selecting same ending day fireEvent.click(getByLabelText('Fri Jan 03 2020')); expect(onSelect).toBeCalledWith(expect.stringMatching(/^2020-01-01T/)); }); test('range as array', () => { const onSelect = jest.fn(); const { getByLabelText } = render( <Grommet> <Calendar dates={[['2020-01-01T00:00:00-08:00', '2020-01-05T00:00:00-08:00']]} onSelect={onSelect} range="array" animate={false} /> </Grommet>, ); // select date greater than January 1st // activeDate by default is start fireEvent.click(getByLabelText('Fri Jan 03 2020')); expect(onSelect).toBeCalledWith([ [ expect.stringMatching(/^2020-01-03T/), expect.stringMatching(/^2020-01-05T/), ], ]); // select date less than January 3rd // activeDate is end, since this is before the start // date we should update the date fireEvent.click(getByLabelText('Wed Jan 01 2020')); expect(onSelect).toBeCalledWith([ [expect.stringMatching(/^2020-01-01T/), undefined], ]); // should select end date again fireEvent.click(getByLabelText('Fri Jan 03 2020')); expect(onSelect).toBeCalledWith([ [ expect.stringMatching(/^2020-01-01T/), expect.stringMatching(/^2020-01-03T/), ], ]); // should select start date, if great than end date, clear end date fireEvent.click(getByLabelText('Sun Jan 05 2020')); expect(onSelect).toBeCalledWith([ [expect.stringMatching(/^2020-01-05T/), undefined], ]); }); test('range as array with date', () => { const onSelect = jest.fn(); const { getByLabelText } = render( <Grommet> <Calendar date={[['2020-01-01T00:00:00-08:00', '2020-01-05T00:00:00-08:00']]} onSelect={onSelect} range="array" animate={false} /> </Grommet>, ); // select date greater than January 1st // activeDate by default is start fireEvent.click(getByLabelText('Fri Jan 03 2020')); expect(onSelect).toBeCalledWith([ [ expect.stringMatching(/^2020-01-03T/), expect.stringMatching(/^2020-01-05T/), ], ]); // select date less than January 3rd // activeDate is end, since this is before the start // date we should update the date fireEvent.click(getByLabelText('Wed Jan 01 2020')); expect(onSelect).toBeCalledWith([ [expect.stringMatching(/^2020-01-01T/), undefined], ]); // should select end date again fireEvent.click(getByLabelText('Fri Jan 03 2020')); expect(onSelect).toBeCalledWith([ [ expect.stringMatching(/^2020-01-01T/), expect.stringMatching(/^2020-01-03T/), ], ]); // should select start date, if great than end date, clear end date fireEvent.click(getByLabelText('Sun Jan 05 2020')); expect(onSelect).toBeCalledWith([ [expect.stringMatching(/^2020-01-05T/), undefined], ]); }); test('activeDate start', () => { const onSelect = jest.fn(); const { getByLabelText } = render( <Grommet> <Calendar activeDate="start" dates={[['2020-01-01T00:00:00-08:00', '2020-01-05T00:00:00-08:00']]} onSelect={onSelect} range="array" animate={false} /> </Grommet>, ); fireEvent.click(getByLabelText('Fri Jan 03 2020')); expect(onSelect).toBeCalledWith([ [ expect.stringMatching(/^2020-01-03T/), expect.stringMatching(/^2020-01-05T/), ], ]); }); test('activeDate end', () => { const onSelect = jest.fn(); const { getByLabelText } = render( <Grommet> <Calendar activeDate="end" dates={[['2020-01-01T00:00:00-08:00', '2020-01-05T00:00:00-08:00']]} onSelect={onSelect} range="array" animate={false} /> </Grommet>, ); fireEvent.click(getByLabelText('Fri Jan 03 2020')); expect(onSelect).toBeCalledWith([ [ expect.stringMatching(/^2020-01-01T/), expect.stringMatching(/^2020-01-03T/), ], ]); }); }); describe('Calendar Keyboard events', () => { let onSelect: CalendarProps['onSelect']; let App: React.FC; beforeEach(() => { onSelect = jest.fn(); App = () => ( <Grommet> <Calendar bounds={['2020-01-01', '2020-01-31']} date={DATE} onSelect={onSelect} animate={false} /> </Grommet> ); }); test('onEnter', async () => { const { getByText } = render(<App />); fireEvent.mouseOver(getByText('15')); fireEvent.click(getByText('15')); fireEvent.keyDown(getByText('15'), { key: 'Enter', keyCode: 13, which: 13, }); fireEvent.mouseOut(getByText('15')); // Jan 15th is set to active expect(onSelect).toBeCalledWith(expect.stringMatching(/^2020-01-15T/)); }); test('onKeyUp', () => { const { getByText } = render(<App />); fireEvent.mouseOver(getByText('15')); fireEvent.click(getByText('15')); fireEvent.keyDown(getByText('15'), { key: 'ArrowUp', keyCode: 38, which: 38, }); // press enter to change date to active fireEvent.keyDown(getByText('15'), { key: 'Enter', keyCode: 13, which: 13, }); // Jan 8th is set to active expect(onSelect).toBeCalledWith(expect.stringMatching(/^2020-01-08T/)); }); test('onKeyDown', () => { const { getByText } = render(<App />); fireEvent.mouseOver(getByText('15')); fireEvent.click(getByText('15')); fireEvent.keyDown(getByText('15'), { key: 'ArrowDown', keyCode: 40, which: 40, }); // press enter to change date to active fireEvent.keyDown(getByText('15'), { key: 'Enter', keyCode: 13, which: 13, }); // Jan 22th is set to active expect(onSelect).toBeCalledWith(expect.stringMatching(/^2020-01-22T/)); }); test('onKeyLeft', () => { const { getByText } = render(<App />); fireEvent.mouseOver(getByText('15')); fireEvent.click(getByText('15')); fireEvent.keyDown(getByText('15'), { key: 'ArrowLeft', keyCode: 37, which: 37, }); // press enter to change date to active fireEvent.keyDown(getByText('15'), { key: 'Enter', keyCode: 13, which: 13, }); // Jan 14th is set to active expect(onSelect).toBeCalledWith(expect.stringMatching(/^2020-01-14T/)); }); test('onKeyRight', () => { const { getByText } = render(<App />); fireEvent.mouseOver(getByText('15')); fireEvent.click(getByText('15')); fireEvent.keyDown(getByText('15'), { key: 'ArrowRight', keyCode: 39, which: 39, }); // press enter to change date to active fireEvent.keyDown(getByText('15'), { key: 'Enter', keyCode: 13, which: 13, }); // Jan 16th is set to active expect(onSelect).toBeCalledWith(expect.stringMatching(/^2020-01-16T/)); }); });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/devicesMappers"; import * as Parameters from "../models/parameters"; import { DataBoxEdgeManagementClientContext } from "../dataBoxEdgeManagementClientContext"; /** Class representing a Devices. */ export class Devices { private readonly client: DataBoxEdgeManagementClientContext; /** * Create a Devices. * @param {DataBoxEdgeManagementClientContext} client Reference to the service client. */ constructor(client: DataBoxEdgeManagementClientContext) { this.client = client; } /** * Gets all the data box edge/gateway devices in a subscription. * @param [options] The optional parameters * @returns Promise<Models.DevicesListBySubscriptionResponse> */ listBySubscription(options?: Models.DevicesListBySubscriptionOptionalParams): Promise<Models.DevicesListBySubscriptionResponse>; /** * @param callback The callback */ listBySubscription(callback: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): void; /** * @param options The optional parameters * @param callback The callback */ listBySubscription(options: Models.DevicesListBySubscriptionOptionalParams, callback: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): void; listBySubscription(options?: Models.DevicesListBySubscriptionOptionalParams | msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>, callback?: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): Promise<Models.DevicesListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec, callback) as Promise<Models.DevicesListBySubscriptionResponse>; } /** * Gets all the data box edge/gateway devices in a resource group. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.DevicesListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: Models.DevicesListByResourceGroupOptionalParams): Promise<Models.DevicesListByResourceGroupResponse>; /** * @param resourceGroupName The resource group name. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): void; /** * @param resourceGroupName The resource group name. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: Models.DevicesListByResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): void; listByResourceGroup(resourceGroupName: string, options?: Models.DevicesListByResourceGroupOptionalParams | msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>, callback?: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): Promise<Models.DevicesListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.DevicesListByResourceGroupResponse>; } /** * Gets the properties of the data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.DevicesGetResponse> */ get(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesGetResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param callback The callback */ get(deviceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.DataBoxEdgeDevice>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param options The optional parameters * @param callback The callback */ get(deviceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataBoxEdgeDevice>): void; get(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataBoxEdgeDevice>, callback?: msRest.ServiceCallback<Models.DataBoxEdgeDevice>): Promise<Models.DevicesGetResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, options }, getOperationSpec, callback) as Promise<Models.DevicesGetResponse>; } /** * Creates or updates a Data Box Edge/Gateway resource. * @param deviceName The device name. * @param dataBoxEdgeDevice The resource object. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.DevicesCreateOrUpdateResponse> */ createOrUpdate(deviceName: string, dataBoxEdgeDevice: Models.DataBoxEdgeDevice, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesCreateOrUpdateResponse> { return this.beginCreateOrUpdate(deviceName,dataBoxEdgeDevice,resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.DevicesCreateOrUpdateResponse>; } /** * Deletes the data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(deviceName,resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Modifies a Data Box Edge/Gateway resource. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.DevicesUpdateResponse> */ update(deviceName: string, resourceGroupName: string, options?: Models.DevicesUpdateOptionalParams): Promise<Models.DevicesUpdateResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param callback The callback */ update(deviceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.DataBoxEdgeDevice>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param options The optional parameters * @param callback The callback */ update(deviceName: string, resourceGroupName: string, options: Models.DevicesUpdateOptionalParams, callback: msRest.ServiceCallback<Models.DataBoxEdgeDevice>): void; update(deviceName: string, resourceGroupName: string, options?: Models.DevicesUpdateOptionalParams | msRest.ServiceCallback<Models.DataBoxEdgeDevice>, callback?: msRest.ServiceCallback<Models.DataBoxEdgeDevice>): Promise<Models.DevicesUpdateResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, options }, updateOperationSpec, callback) as Promise<Models.DevicesUpdateResponse>; } /** * @summary Downloads the updates on a data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ downloadUpdates(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDownloadUpdates(deviceName,resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Gets additional information for the specified data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.DevicesGetExtendedInformationResponse> */ getExtendedInformation(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesGetExtendedInformationResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param callback The callback */ getExtendedInformation(deviceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.DataBoxEdgeDeviceExtendedInfo>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param options The optional parameters * @param callback The callback */ getExtendedInformation(deviceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataBoxEdgeDeviceExtendedInfo>): void; getExtendedInformation(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataBoxEdgeDeviceExtendedInfo>, callback?: msRest.ServiceCallback<Models.DataBoxEdgeDeviceExtendedInfo>): Promise<Models.DevicesGetExtendedInformationResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, options }, getExtendedInformationOperationSpec, callback) as Promise<Models.DevicesGetExtendedInformationResponse>; } /** * @summary Installs the updates on the data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ installUpdates(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginInstallUpdates(deviceName,resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Gets the network settings of the specified data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.DevicesGetNetworkSettingsResponse> */ getNetworkSettings(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesGetNetworkSettingsResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param callback The callback */ getNetworkSettings(deviceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.NetworkSettings>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param options The optional parameters * @param callback The callback */ getNetworkSettings(deviceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NetworkSettings>): void; getNetworkSettings(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NetworkSettings>, callback?: msRest.ServiceCallback<Models.NetworkSettings>): Promise<Models.DevicesGetNetworkSettingsResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, options }, getNetworkSettingsOperationSpec, callback) as Promise<Models.DevicesGetNetworkSettingsResponse>; } /** * @summary Scans for updates on a data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ scanForUpdates(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginScanForUpdates(deviceName,resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Updates the security settings on a data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param deviceAdminPassword Device administrator password as an encrypted string (encrypted using * RSA PKCS #1) is used to sign into the local web UI of the device. The Actual password should * have at least 8 characters that are a combination of uppercase, lowercase, numeric, and special * characters. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ createOrUpdateSecuritySettings(deviceName: string, resourceGroupName: string, deviceAdminPassword: Models.AsymmetricEncryptedSecret, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginCreateOrUpdateSecuritySettings(deviceName,resourceGroupName,deviceAdminPassword,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * @summary Gets information about the availability of updates based on the last scan of the * device. It also gets information about any ongoing download or install jobs on the device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.DevicesGetUpdateSummaryResponse> */ getUpdateSummary(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesGetUpdateSummaryResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param callback The callback */ getUpdateSummary(deviceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.UpdateSummary>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param options The optional parameters * @param callback The callback */ getUpdateSummary(deviceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.UpdateSummary>): void; getUpdateSummary(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.UpdateSummary>, callback?: msRest.ServiceCallback<Models.UpdateSummary>): Promise<Models.DevicesGetUpdateSummaryResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, options }, getUpdateSummaryOperationSpec, callback) as Promise<Models.DevicesGetUpdateSummaryResponse>; } /** * Uploads registration certificate for the device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param certificate The base64 encoded certificate raw data. * @param [options] The optional parameters * @returns Promise<Models.DevicesUploadCertificateResponse> */ uploadCertificate(deviceName: string, resourceGroupName: string, certificate: string, options?: Models.DevicesUploadCertificateOptionalParams): Promise<Models.DevicesUploadCertificateResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param certificate The base64 encoded certificate raw data. * @param callback The callback */ uploadCertificate(deviceName: string, resourceGroupName: string, certificate: string, callback: msRest.ServiceCallback<Models.UploadCertificateResponse>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param certificate The base64 encoded certificate raw data. * @param options The optional parameters * @param callback The callback */ uploadCertificate(deviceName: string, resourceGroupName: string, certificate: string, options: Models.DevicesUploadCertificateOptionalParams, callback: msRest.ServiceCallback<Models.UploadCertificateResponse>): void; uploadCertificate(deviceName: string, resourceGroupName: string, certificate: string, options?: Models.DevicesUploadCertificateOptionalParams | msRest.ServiceCallback<Models.UploadCertificateResponse>, callback?: msRest.ServiceCallback<Models.UploadCertificateResponse>): Promise<Models.DevicesUploadCertificateResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, certificate, options }, uploadCertificateOperationSpec, callback) as Promise<Models.DevicesUploadCertificateResponse>; } /** * Creates or updates a Data Box Edge/Gateway resource. * @param deviceName The device name. * @param dataBoxEdgeDevice The resource object. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(deviceName: string, dataBoxEdgeDevice: Models.DataBoxEdgeDevice, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, dataBoxEdgeDevice, resourceGroupName, options }, beginCreateOrUpdateOperationSpec, options); } /** * Deletes the data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, resourceGroupName, options }, beginDeleteMethodOperationSpec, options); } /** * @summary Downloads the updates on a data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDownloadUpdates(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, resourceGroupName, options }, beginDownloadUpdatesOperationSpec, options); } /** * @summary Installs the updates on the data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginInstallUpdates(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, resourceGroupName, options }, beginInstallUpdatesOperationSpec, options); } /** * @summary Scans for updates on a data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginScanForUpdates(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, resourceGroupName, options }, beginScanForUpdatesOperationSpec, options); } /** * Updates the security settings on a data box edge/gateway device. * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param deviceAdminPassword Device administrator password as an encrypted string (encrypted using * RSA PKCS #1) is used to sign into the local web UI of the device. The Actual password should * have at least 8 characters that are a combination of uppercase, lowercase, numeric, and special * characters. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdateSecuritySettings(deviceName: string, resourceGroupName: string, deviceAdminPassword: Models.AsymmetricEncryptedSecret, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, resourceGroupName, deviceAdminPassword, options }, beginCreateOrUpdateSecuritySettingsOperationSpec, options); } /** * Gets all the data box edge/gateway devices in a subscription. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.DevicesListBySubscriptionNextResponse> */ listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesListBySubscriptionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): void; listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>, callback?: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): Promise<Models.DevicesListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listBySubscriptionNextOperationSpec, callback) as Promise<Models.DevicesListBySubscriptionNextResponse>; } /** * Gets all the data box edge/gateway devices in a resource group. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.DevicesListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>, callback?: msRest.ServiceCallback<Models.DataBoxEdgeDeviceList>): Promise<Models.DevicesListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.DevicesListByResourceGroupNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listBySubscriptionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion, Parameters.expand ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataBoxEdgeDeviceList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion, Parameters.expand ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataBoxEdgeDeviceList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataBoxEdgeDevice }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: { tags: [ "options", "tags" ] }, mapper: { ...Mappers.DataBoxEdgeDevicePatch, required: true } }, responses: { 200: { bodyMapper: Mappers.DataBoxEdgeDevice }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getExtendedInformationOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/getExtendedInformation", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataBoxEdgeDeviceExtendedInfo }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getNetworkSettingsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/networkSettings/default", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.NetworkSettings }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getUpdateSummaryOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/updateSummary/default", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.UpdateSummary }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const uploadCertificateOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/uploadCertificate", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: { authenticationType: [ "options", "authenticationType" ], certificate: "certificate" }, mapper: { ...Mappers.UploadCertificateRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.UploadCertificateResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "dataBoxEdgeDevice", mapper: { ...Mappers.DataBoxEdgeDevice, required: true } }, responses: { 200: { bodyMapper: Mappers.DataBoxEdgeDevice }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDownloadUpdatesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/downloadUpdates", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginInstallUpdatesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/installUpdates", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginScanForUpdatesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/scanForUpdates", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateSecuritySettingsOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/securitySettings/default/update", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: { deviceAdminPassword: "deviceAdminPassword" }, mapper: { ...Mappers.SecuritySettings, required: true } }, responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listBySubscriptionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataBoxEdgeDeviceList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataBoxEdgeDeviceList }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
/// <reference types="@types/styled-system" /> /* Note: Using this syntax instead of synthetic default export because we shouldn't assume the TS compiler * options used by DS consumers. */ import * as React from 'react' import { AlignItemsProps, BorderColorProps, BorderRadiusProps, BordersProps, BottomProps, FlexDirectionProps, FlexWrapProps, FontSizeProps, FontWeightProps, JustifyContentProps, LeftProps, LineHeightProps, ResponsiveValue, RightProps, SizeProps, SpaceProps, TextAlignProps, TextColorProps, TextStyleProps, Theme, TLengthStyledSystem, TopProps, WidthProps, ZIndexProps, } from 'styled-system' import * as CSS from 'csstype' /** * Helper interfaces */ export interface ColorValidation { color?: PropValidator } export interface ReactRefObject { current: any } export interface ClassNameProps { className?: string } export interface TopRightBottomLeft extends TopProps, RightProps, BottomProps, LeftProps {} export type RefPropType = (() => any) | ReactRefObject export type PropValidator = undefined | never export interface DsRefProps { dsRef?: (() => any) | ReactRefObject } export interface IdProps { id: string } export interface BoxShadowSizeProps { /** Add a box shadow with a size based on values defined in the theme */ boxShadowSize?: 'sm' | 'md' | 'lg' | 'xl' } export interface ColorProps<TLength = TLengthStyledSystem> { /** * DEPRECATED: Use "color" prop instead. * * The "bg" prop will be removed in v4 in favor of "color", which sets both the background * and font color. Font color is based on the background color set via the "color" prop. This is * to avoid accessibility issues with certain combinations of text and background colors. * * [See GitHub issue for more details](https://github.com/priceline/design-system/issues/650) */ bg?: ResponsiveValue<CSS.BackgroundProperty<TLength>> /** * Sets the background color of the component to the given semantic color. Also sets the text color * based on the theme and the given semantic color name to ensure an accessible contrast level. * * [See the docsite for the list of semantic color names](https://priceline.github.io/design-system/palette) */ color?: string // TODO replace with type that enumerates semantic color names, as well as combinations of colors and shades } /** * Combining Styled System interfaces depending on which Styled System functions * the component uses */ export type AbsoluteProps = TopRightBottomLeft export interface BackgroundImageProps extends WidthProps { height?: string /** URL of background image */ image?: string variation?: 'parallax' | 'static' } export interface BadgeProps extends ColorProps, SpaceProps { size?: 'small' | 'medium' } export interface BoxProps extends ColorProps, BoxShadowSizeProps, WidthProps, SpaceProps, TextAlignProps {} export interface ButtonBaseProps extends ColorProps, SpaceProps, WidthProps, React.ButtonHTMLAttributes<any> { dsRef?: RefPropType } export interface ButtonProps extends ButtonBaseProps { size?: 'small' | 'medium' | 'large' variation?: 'fill' | 'outline' | 'link' /** DEPRECATED: Use "width" prop instead */ fullWidth?: boolean } export interface BreadcrumbLinkProps { /** This is the last link in the breadcrumbs list */ isLastChild?: boolean href?: string icon?: React.ComponentElement<IconProps, any> label?: string dsRef?: RefPropType onClick?: (any) => void } export interface FlexProps extends BoxProps, JustifyContentProps, FlexWrapProps, AlignItemsProps, FlexDirectionProps { /** DEPRECATED: Use "flexWrap" prop instead */ wrap?: ResponsiveValue<CSS.FlexWrapProperty> /** DEPRECATED: Use "alignItems" prop instead */ align?: ResponsiveValue<CSS.AlignItemsProperty> /** DEPRECATED: Use "justifyContent" prop instead */ justify?: ResponsiveValue<CSS.JustifyContentProperty> } export interface HideProps extends BoxProps { xs?: boolean sm?: boolean md?: boolean lg?: boolean xl?: boolean xxl?: boolean print?: boolean } export interface IconProps extends ColorProps, SizeProps { name?: string title?: string titleId?: string desc?: string descId?: string } export interface IconButtonProps extends ButtonProps { icon?: React.ComponentElement<IconProps, any> } export interface CardProps extends BoxProps, BorderRadiusProps, BoxShadowSizeProps, BorderColorProps { borderWidth?: 0 | 1 | 2 } export interface CloseButtonProps extends ButtonBaseProps, ColorProps, SpaceProps, WidthProps { dsRef?: RefPropType size?: number variation?: 'fill' | 'outline' | 'link' /** DEPRECATED: Use "width" prop instead */ fullWidth?: boolean title?: string } export interface ImageProps extends WidthProps { height?: string alt?: string src: string } export interface LinkProps extends TextColorProps { variation?: 'fill' | 'link' | 'outline' dsRef?: RefPropType } export interface PlaceholderImageProps { /** Alternate text */ alt?: string /** Sets aria-hidden attribute */ ariaHidden?: boolean /** Image should be blurred */ blur?: boolean /** Choose a specific placeholder image from the array of default images */ chooseSrc?: string /** Sets img height attribute */ height?: string /** Sets img width attribute */ width?: string } export interface RatingBadgeProps extends BoxProps, BorderRadiusProps, FontWeightProps {} export interface RelativeProps extends TopRightBottomLeft, BoxProps, ZIndexProps {} export interface StepProps extends ButtonProps, ClassNameProps { active?: boolean completed?: boolean } export interface ToggleBadgeProps extends ColorProps, FontSizeProps, SpaceProps { dsRef?: RefPropType selected?: boolean unSelectedBg?: string } export interface TextProps<TLength = TLengthStyledSystem> extends TextStyleProps, FontSizeProps, FontWeightProps, TextAlignProps, LineHeightProps, SpaceProps, TextColorProps { /** Sets font-weight: props.theme.regular */ regular?: boolean /** Sets font-weight: props.theme.bold */ bold?: boolean /** Sets styles for all-caps type treatments */ caps?: boolean /** Sets styles for italic type treatments */ italic?: boolean enableTextShadow?: boolean textShadowSize?: 'sm' | 'md' /** DEPRECATED: Use "textAlign" prop instead */ align?: ResponsiveValue<CSS.TextAlignProperty> /** Sets background color */ bg?: ResponsiveValue<CSS.BackgroundProperty<TLength>> } export interface DSTheme extends Theme { palette?: any } export interface ThemeProviderProps { theme?: DSTheme customBreakpoints?: string[] } export interface DividerProps extends ColorProps, SpaceProps, WidthProps, BorderColorProps {} export interface AvatarProps extends ClassNameProps, ColorProps { /** Heading displayed with avatar */ title?: string /** Subheading displayed beneath heading */ subtitle?: string src?: string /** Alternative initials to display when src is not provided */ initials?: string /** Size in px to use for height, width, and background-size */ size?: number } export interface BannerProps extends BoxProps { header?: string | React.ReactNode icon?: React.ComponentElement<IconProps, any> onClose?: (any) => void showIcon?: boolean text?: string | React.ReactNode } export interface StampProps extends SpaceProps, FontSizeProps, ColorProps { variation?: 'outline' | 'fill' | 'solid' size?: 'small' | 'medium' } export interface ContainerProps { maxWidth?: number } export interface FlagProps extends FlexProps, WidthProps {} export interface HugProps extends CardProps { iconDisplay?: string icon?: React.ComponentElement<IconProps, any> text?: React.ReactNode | string } export interface TooltipProps extends BoxProps { zIndex?: number | string bottom?: boolean top?: boolean center?: boolean left?: boolean right?: boolean } export interface CheckboxProps extends DsRefProps, ColorValidation { id: string size?: number onChange: () => void } export interface LabelProps extends SpaceProps, FontSizeProps, FontWeightProps, WidthProps, TextColorProps {} export interface RadioProps extends TextColorProps, DsRefProps { size?: number } export interface SelectProps extends DsRefProps, SpaceProps, FontSizeProps, TextColorProps, BordersProps {} export interface TextAreaProps extends TextColorProps, DsRefProps, BordersProps, SpaceProps, IdProps {} export interface InputProps extends DsRefProps, BordersProps, SpaceProps, TextColorProps, FontSizeProps {} export interface InputGroupProps extends SpaceProps, BorderColorProps {} // // pcln-design-system components // ------------------------------------------------------------ export class Absolute extends React.Component< AbsoluteProps & React.HTMLProps<HTMLDivElement> > {} export class Avatar extends React.Component< AvatarProps & React.HTMLProps<HTMLDivElement> > {} export class BackgroundImage extends React.Component<BackgroundImageProps> {} export class Badge extends React.Component<BadgeProps> {} export class Banner extends React.Component< BannerProps & React.HTMLProps<HTMLDivElement> > {} export class BlockLink extends React.Component< LinkProps & React.HTMLProps<HTMLAnchorElement> > {} export class Box extends React.Component< BoxProps & React.HTMLProps<HTMLAnchorElement> > {} export class Breadcrumbs extends React.Component< React.HTMLProps<HTMLDivElement> > { static Link: typeof BreadcrumbLink } export class BreadcrumbLink extends React.Component< BreadcrumbLinkProps & React.HTMLProps<HTMLAnchorElement> > {} export class Button extends React.Component<ButtonProps> {} export class Card extends React.Component< CardProps & React.HTMLProps<HTMLDivElement> > {} export class Checkbox extends React.Component< CheckboxProps & React.HTMLProps<HTMLInputElement> > {} export class CloseButton extends React.Component< CloseButtonProps & React.HTMLProps<HTMLButtonElement> > {} export class Container extends React.Component< ContainerProps & React.HTMLProps<HTMLDivElement> > {} export class Divider extends React.Component< DividerProps & React.HTMLProps<HTMLDivElement> > {} export class Flag extends React.Component< FlagProps & React.HTMLProps<HTMLDivElement> > {} export class Flex extends React.Component< FlexProps & React.HTMLProps<HTMLDivElement> > {} export class FormField extends React.Component< React.HTMLProps<HTMLDivElement> > {} export class Heading extends React.Component< TextProps & React.HTMLProps<HTMLDivElement> > { static h1: typeof Heading static h2: typeof Heading static h3: typeof Heading static h4: typeof Heading static h5: typeof Heading static h6: typeof Heading } export class Hide extends React.Component< HideProps & React.HTMLProps<HTMLDivElement> > {} export class Hug extends React.Component< HugProps & React.HTMLProps<HTMLDivElement> > {} export class Icon extends React.Component< IconProps & React.HTMLProps<HTMLDivElement> > {} export class IconButton extends React.Component<IconButtonProps> {} export class IconField extends React.Component< FlexProps & React.HTMLProps<HTMLDivElement> > {} export class Image extends React.Component<ImageProps> {} export class Input extends React.Component< InputProps & React.HTMLProps<HTMLButtonElement> > { static isField: boolean } export class InputGroup extends React.Component< InputGroupProps & React.HTMLProps<HTMLDivElement> > {} export class Label extends React.Component< LabelProps & React.HTMLProps<HTMLLabelElement> > { static isLabel: boolean } export class Link extends React.Component< LinkProps & React.HTMLProps<HTMLAnchorElement> > {} export class PlaceholderImage extends React.Component< PlaceholderImageProps & React.HTMLProps<HTMLImageElement> > {} export class Radio extends React.Component< RadioProps & React.HTMLProps<HTMLInputElement> > {} export class RatingBadge extends React.Component< RatingBadgeProps & React.HTMLProps<HTMLDivElement> > {} export class Relative extends React.Component< RelativeProps & React.HTMLProps<HTMLDivElement> > {} export class Select extends React.Component< SelectProps & React.HTMLProps<HTMLSelectElement> > { static isField: boolean } export class Stamp extends React.Component<StampProps> {} export class Step extends React.Component< StepProps & React.HTMLProps<HTMLDivElement> > {} export class Stepper extends React.Component< ClassNameProps & React.HTMLProps<HTMLDivElement> > { static Step: typeof Step } export class SrOnly extends React.Component<React.HTMLProps<HTMLSpanElement>> {} export class Text extends React.Component< TextProps & React.HTMLProps<HTMLDivElement> > { /** Span element */ static span /** Paragraph element */ static p /** Strikethrough element */ static s } export class TextArea extends React.Component< TextAreaProps & React.HTMLProps<HTMLTextAreaElement> > { static isField: boolean } export class ThemeProvider extends React.Component< ThemeProviderProps & React.HTMLProps<HTMLDivElement> > {} export class ToggleBadge extends React.Component< ToggleBadgeProps & React.HTMLProps<HTMLDivElement> > {} export class Tooltip extends React.Component< TooltipProps & React.HTMLProps<HTMLDivElement> > {} export class Truncate extends React.Component< TextProps & React.HTMLProps<HTMLDivElement> > {} // // pcln-design-system utils // ------------------------------------------------------------ export interface ThemeArgs { theme: Theme } export interface ColorArgs extends ThemeArgs { color?: string bg?: string } export interface CustomBreakpoints { [key: string]: string | number } export interface PaletteColor { lightest?: string light?: string base: string dark?: string darkest?: string } export interface Palette { [key: string]: PaletteColor } export interface CreateThemeResult extends Theme { contrastRatio: number breakpoints: any[] mediaQueries: any[] palette: Palette } export function getContrastRatio(colorA: string, colorB: string): number export function deprecatedPropType(replacement: string): Error | undefined export function borders(props: ThemeArgs): object export function hasPaletteColor(props: ThemeArgs): boolean export function color(props: ColorArgs): string[] | string export function getPaletteColor( color: string, shade?: string ): (props: ThemeArgs) => any export function getTextColorOn(name: string): (props: ThemeArgs) => any export function createTheme( theme: Theme, customBreakpoints: CustomBreakpoints ): CreateThemeResult export type theme = Theme
the_stack
import fetch from "node-fetch"; import md5 from "md5"; import Users from "../../lib/collections/users/collection"; import { userGetGroups } from '../../lib/vulcan-users/permissions'; import { updateMutator } from '../vulcan-lib/mutators'; import { Posts } from '../../lib/collections/posts' import { Comments } from '../../lib/collections/comments' import { bellNotifyEmailVerificationRequired } from '../notificationCallbacks'; import { isAnyTest } from '../../lib/executionEnvironment'; import { randomId } from '../../lib/random'; import { getCollectionHooks } from '../mutationCallbacks'; import { voteCallbacks, VoteDocTuple } from '../../lib/voting/vote'; import { encodeIntlError } from '../../lib/vulcan-lib/utils'; import { userFindByEmail } from '../../lib/vulcan-users/helpers'; import { sendVerificationEmail } from "../vulcan-lib/apollo-server/authentication"; import { forumTypeSetting } from "../../lib/instanceSettings"; import { mailchimpEAForumListIdSetting, mailchimpForumDigestListIdSetting } from "../../lib/publicSettings"; import { mailchimpAPIKeySetting } from "../../server/serverSettings"; import { userGetLocation } from "../../lib/collections/users/helpers"; import { captureException } from "@sentry/core"; const MODERATE_OWN_PERSONAL_THRESHOLD = 50 const TRUSTLEVEL1_THRESHOLD = 2000 voteCallbacks.castVoteAsync.add(async function updateTrustedStatus ({newDocument, vote}: VoteDocTuple) { const user = await Users.findOne(newDocument.userId) if (user && user.karma >= TRUSTLEVEL1_THRESHOLD && (!userGetGroups(user).includes('trustLevel1'))) { await Users.rawUpdateOne(user._id, {$push: {groups: 'trustLevel1'}}); const updatedUser = await Users.findOne(newDocument.userId) //eslint-disable-next-line no-console console.info("User gained trusted status", updatedUser?.username, updatedUser?._id, updatedUser?.karma, updatedUser?.groups) } }); voteCallbacks.castVoteAsync.add(async function updateModerateOwnPersonal({newDocument, vote}: VoteDocTuple) { const user = await Users.findOne(newDocument.userId) if (!user) throw Error("Couldn't find user") if (user.karma >= MODERATE_OWN_PERSONAL_THRESHOLD && (!userGetGroups(user).includes('canModeratePersonal'))) { await Users.rawUpdateOne(user._id, {$push: {groups: 'canModeratePersonal'}}); const updatedUser = await Users.findOne(newDocument.userId) if (!updatedUser) throw Error("Couldn't find user to update") //eslint-disable-next-line no-console console.info("User gained trusted status", updatedUser.username, updatedUser._id, updatedUser.karma, updatedUser.groups) } }); getCollectionHooks("Users").editSync.add(function maybeSendVerificationEmail (modifier, user: DbUser) { if(modifier.$set.whenConfirmationEmailSent && (!user.whenConfirmationEmailSent || user.whenConfirmationEmailSent.getTime() !== modifier.$set.whenConfirmationEmailSent.getTime())) { void sendVerificationEmail(user); } }); getCollectionHooks("Users").editAsync.add(async function approveUnreviewedSubmissions (newUser: DbUser, oldUser: DbUser) { if(newUser.reviewedByUserId && !oldUser.reviewedByUserId) { // For each post by this author which has the authorIsUnreviewed flag set, // clear the authorIsUnreviewed flag so it's visible, and update postedAt // to now so that it goes to the right place int he latest posts list. const unreviewedPosts = await Posts.find({userId:newUser._id, authorIsUnreviewed:true}).fetch(); for (let post of unreviewedPosts) { await updateMutator<DbPost>({ collection: Posts, documentId: post._id, set: { authorIsUnreviewed: false, postedAt: new Date(), }, validate: false }); } // Also clear the authorIsUnreviewed flag on comments. We don't want to // reset the postedAt for comments, since those are by default visible // almost everywhere. This can bypass the mutation system fine, because the // flag doesn't control whether they're indexed in Algolia. await Comments.rawUpdateMany({userId:newUser._id, authorIsUnreviewed:true}, {$set:{authorIsUnreviewed:false}}, {multi: true}) } }); getCollectionHooks("Users").editAsync.add(function mapLocationMayTriggerReview(newUser: DbUser, oldUser: DbUser) { // on the EA Forum, we are testing out reviewing all unreviewed users who add a bio const addedBio = !oldUser.biography?.html && newUser.biography?.html && forumTypeSetting.get() === 'EAForum' // if the user has a mapLocation and they have not been reviewed, mark them for review if ((addedBio || newUser.mapLocation) && !newUser.reviewedByUserId && !newUser.needsReview) { void Users.rawUpdateOne({_id: newUser._id}, {$set: {needsReview: true}}) } }) // When the very first user account is being created, add them to Sunshine // Regiment. Patterned after a similar callback in // vulcan-users/lib/server/callbacks.js which makes the first user an admin. getCollectionHooks("Users").newSync.add(async function makeFirstUserAdminAndApproved (user: DbUser) { if (isAnyTest) return user; const realUsersCount = await Users.find({}).count(); if (realUsersCount === 0) { user.reviewedByUserId = "firstAccount"; //HACK // Add the first user to the Sunshine Regiment if (!user.groups) user.groups = []; user.groups.push("sunshineRegiment"); } return user; }); getCollectionHooks("Users").editSync.add(function clearKarmaChangeBatchOnSettingsChange (modifier, user: DbUser) { if (modifier.$set && modifier.$set.karmaChangeNotifierSettings) { if (!user.karmaChangeNotifierSettings.updateFrequency || modifier.$set.karmaChangeNotifierSettings.updateFrequency !== user.karmaChangeNotifierSettings.updateFrequency) { modifier.$set.karmaChangeLastOpened = null; modifier.$set.karmaChangeBatchStart = null; } } }); getCollectionHooks("Users").newAsync.add(async function subscribeOnSignup (user: DbUser) { // Regardless of the config setting, try to confirm the user's email address // (But not in unit-test contexts, where this function is unavailable and sending // emails doesn't make sense.) if (!isAnyTest && forumTypeSetting.get() !== 'EAForum') { void sendVerificationEmail(user); if (user.emailSubscribedToCurated) { await bellNotifyEmailVerificationRequired(user); } } }); // When creating a new account, populate their A/B test group key from their // client ID, so that their A/B test groups will persist from when they were // logged out. getCollectionHooks("Users").newAsync.add(async function setABTestKeyOnSignup (user: DbInsertion<DbUser>) { if (!user.abTestKey) { const abTestKey = user.profile?.clientId || randomId(); await Users.rawUpdateOne(user._id, {$set: {abTestKey: abTestKey}}); } }); getCollectionHooks("Users").editAsync.add(async function handleSetShortformPost (newUser: DbUser, oldUser: DbUser) { if (newUser.shortformFeedId !== oldUser.shortformFeedId) { const post = await Posts.findOne({_id: newUser.shortformFeedId}); if (!post) throw new Error("Invalid post ID for shortform"); if (post.userId !== newUser._id) throw new Error("Post can only be an author's short-form post if they are the post's author"); if (post.draft) throw new Error("Draft post cannot be a user's short-form post"); // @ts-ignore -- this should be something with post.status; post.deleted doesn't exist if (post.deleted) throw new Error("Deleted post cannot be a user's short-form post"); // In theory, we should check here whether the user already had a short-form // post which is getting un-set, and clear the short-form flag from it. But // in the long run we won't need to do this, because creation of short-form // posts will be automatic-only, and as admins we can just not click the // set-as-shortform button on posts for users that already have a shortform. // So, don't bother checking for an old post in the shortformFeedId field. // Mark the post as shortform await updateMutator({ collection: Posts, documentId: post._id, set: { shortform: true }, unset: {}, validate: false, }); } }); getCollectionHooks("Users").newSync.add(async function usersMakeAdmin (user: DbUser) { if (isAnyTest) return user; // if this is not a dummy account, and is the first user ever, make them an admin // TODO: should use await Connectors.count() instead, but cannot await inside Accounts.onCreateUser. Fix later. if (typeof user.isAdmin === 'undefined') { const realUsersCount = await Users.find({}).count(); user.isAdmin = (realUsersCount === 0); } return user; }); getCollectionHooks("Users").editSync.add(async function usersEditCheckEmail (modifier, user: DbUser) { // if email is being modified, update user.emails too if (modifier.$set && modifier.$set.email) { const newEmail = modifier.$set.email; // check for existing emails and throw error if necessary const userWithSameEmail = await userFindByEmail(newEmail); if (userWithSameEmail && userWithSameEmail._id !== user._id) { throw new Error(encodeIntlError({id:'users.email_already_taken', value: newEmail})); } // if user.emails exists, change it too if (!!user.emails && user.emails.length) { if (user.emails[0].address !== newEmail) { user.emails[0].address = newEmail; user.emails[0].verified = false; modifier.$set.emails = user.emails; } } else { modifier.$set.emails = [{address: newEmail, verified: false}]; } } return modifier; }); getCollectionHooks("Users").editAsync.add(async function subscribeToForumDigest (newUser: DbUser, oldUser: DbUser) { if ( isAnyTest || forumTypeSetting.get() !== 'EAForum' || newUser.subscribedToDigest === oldUser.subscribedToDigest ) { return; } const mailchimpAPIKey = mailchimpAPIKeySetting.get(); const mailchimpForumDigestListId = mailchimpForumDigestListIdSetting.get(); if (!mailchimpAPIKey || !mailchimpForumDigestListId) { return; } if (!newUser.email) { captureException(new Error(`Forum digest subscription failed: no email for user ${newUser.displayName}`)) return; } const { lat: latitude, lng: longitude, known } = userGetLocation(newUser); const status = newUser.subscribedToDigest ? 'subscribed' : 'unsubscribed'; const emailHash = md5(newUser.email.toLowerCase()); void fetch(`https://us8.api.mailchimp.com/3.0/lists/${mailchimpForumDigestListId}/members/${emailHash}`, { method: 'PUT', body: JSON.stringify({ email_address: newUser.email, email_type: 'html', ...(known && {location: { latitude, longitude, }}), merge_fields: { FNAME: newUser.displayName, }, status, }), headers: { 'Content-Type': 'application/json', Authorization: `API_KEY ${mailchimpAPIKey}`, }, }).catch(e => { captureException(e); // eslint-disable-next-line no-console console.log(e); }); }); /** * This callback adds all new users to an audience in Mailchimp which will be used for a forthcoming * (as of 2021-08-11) drip campaign. */ getCollectionHooks("Users").newAsync.add(async function subscribeToEAForumAudience(user: DbUser) { if (isAnyTest || forumTypeSetting.get() !== 'EAForum') { return; } const mailchimpAPIKey = mailchimpAPIKeySetting.get(); const mailchimpEAForumListId = mailchimpEAForumListIdSetting.get(); if (!mailchimpAPIKey || !mailchimpEAForumListId) { return; } if (!user.email) { captureException(new Error(`Subscription to EA Forum audience failed: no email for user ${user.displayName}`)) return; } const { lat: latitude, lng: longitude, known } = userGetLocation(user); void fetch(`https://us8.api.mailchimp.com/3.0/lists/${mailchimpEAForumListId}/members`, { method: 'POST', body: JSON.stringify({ email_address: user.email, email_type: 'html', ...(known && {location: { latitude, longitude, }}), status: "subscribed", }), headers: { 'Content-Type': 'application/json', Authorization: `API_KEY ${mailchimpAPIKey}`, }, }).catch(e => { captureException(e); // eslint-disable-next-line no-console console.log(e); }); });
the_stack
import { ComponentType } from 'react' import { Animated, ViewStyle } from 'react-native' /* ======================== ======================== * * ======================== INTERNAL TYPES ======================== * * ======================== ======================== */ export type ModalfyParams = { [key: string]: any } export type ModalTransitionValue = | Animated.AnimatedInterpolation | string | number | undefined | null export type ModalTransitionOptions = ( animatedValue: Animated.Value, ) => { [key: string]: | { [key: string]: ModalTransitionValue }[] | ModalTransitionValue } export type ModalEventName = 'onAnimate' export type ModalEventAction = 'add' export type ModalEventPayload = { eventName: ModalEventName handler: ModalEventCallback } export type ModalEventCallback = (value?: number) => void export type ModalEventListener = { remove: () => boolean } export type ModalListener = ( eventName: ModalEventName, callback: ModalEventCallback, ) => ModalEventListener export type ModalEventListeners = Set<{ event: string handler: ModalEventCallback }> export interface ModalStackItem<P extends ModalfyParams> { name: Exclude<keyof P, symbol | number> component: ComponentType<any> & { modalOptions?: ModalOptions } hash: string index: number options?: ModalOptions params?: any } export interface ModalStack<P extends ModalfyParams> { names: Array<Exclude<keyof P, symbol | number>> content: ModalStackItem<P>[] defaultOptions: ModalOptions openedItems: Set<ModalStackItem<P>> openedItemsSize: number } export interface ModalContextProvider< P extends ModalfyParams, M extends Exclude<keyof P, symbol | number> = Exclude< keyof P, symbol | number > > { currentModal: M | null closeAllModals: () => void closeModal: (stackItem?: M | ModalStackItem<P>) => void closeModals: (modalName: M) => boolean getParam: <N extends keyof P[M], D extends P[M][N]>( hash: ModalStackItem<P>['hash'], paramName: N, defaultValue?: D, ) => D extends P[M][N] ? P[M][N] : undefined openModal: <N extends M>(modalName: N, params?: P[N]) => void stack: ModalStack<P> } export interface ModalStateSubscriber<P> { state: { currentModal: ModalContextProvider<P>['currentModal'] stack: ModalContextProvider<P>['stack'] } equalityFn: ModalStateEqualityChecker<P> error: boolean listener: ModalStateListener<P> unsubscribe: () => void } export interface ModalStateSubscription<P> { unsubscribe: ModalStateSubscriber<P>['unsubscribe'] } export type ModalStateListener<P> = ( state: { currentModal: ModalContextProvider<P>['currentModal'] stack: ModalContextProvider<P>['stack'] } | null, error?: Error, ) => void export type ModalStateEqualityChecker<P> = ( currentState: { currentModal: ModalContextProvider<P>['currentModal'] stack: ModalContextProvider<P>['stack'] }, newState: { currentModal: ModalContextProvider<P>['currentModal'] stack: ModalContextProvider<P>['stack'] }, ) => boolean export type ModalState<P> = Omit< ModalContextProvider<P>, 'currentModal' | 'stack' | 'openModal' > & { openModal: <M extends Exclude<keyof P, symbol | number>, N extends M>( modalName: N, params?: P[N], isCalledOutsideOfContext?: boolean, ) => void handleBackPress(): boolean init: <P>(newState: { currentModal: ModalContextProvider<P>['currentModal'] stack: ModalContextProvider<P>['stack'] }) => { currentModal: ModalContextProvider<P>['currentModal'] stack: ModalContextProvider<P>['stack'] } getState: <P>() => { currentModal: ModalContextProvider<P>['currentModal'] stack: ModalContextProvider<P>['stack'] } setState: <P>(newState: { currentModal: ModalContextProvider<P>['currentModal'] stack: ModalContextProvider<P>['stack'] }) => void subscribe: <P>( listener: ModalStateListener<P>, equalityFn?: ModalStateEqualityChecker<P>, ) => ModalStateSubscription<P> } export interface SharedProps<P extends ModalfyParams> extends ModalContextProvider<P> { clearListeners: (hash: string) => void eventListeners: ModalEventListeners registerListener: ( hash: ModalStackItem<P>['hash'], eventName: ModalEventName, handler: ModalEventCallback, ) => ModalEventListener } export type UsableModalProp<P extends ModalfyParams> = Pick< ModalContextProvider<P>, 'closeAllModals' | 'closeModals' | 'currentModal' | 'openModal' > & { closeModal: (modalName?: Exclude<keyof P, symbol | number>) => void } export interface UsableModalComponentProp< P extends ModalfyParams, M extends keyof P > extends Omit<ModalContextProvider<P>, 'closeModal' | 'stack' | 'getParam'> { addListener: ModalListener closeModal: (modalName?: M) => void getParam: <N extends keyof P[M], D extends P[M][N]>( paramName: N, defaultValue?: D, ) => D extends P[M][N] ? P[M][N] : undefined removeAllListeners: () => void params?: P[M] } /* ======================== ======================== * * ======================== CONSUMER TYPES ======================== * * ======================== ======================== */ /** * Interface of the modal stack configuration. * These settings will let Modalfy know what modals you will be rendering and how. * * @see https://colorfy-software.gitbook.io/react-native-modalfy/guides/typing#config-and-options */ export interface ModalStackConfig { [key: string]: ComponentType<any> | ModalOptions } /** * Interface of the modal configuration options. * These settings will let Modalfy how to render and animate a modal. * * @see https://colorfy-software.gitbook.io/react-native-modalfy/guides/typing#config-and-options */ export interface ModalOptions { /** * Animation configuration used to animate a modal in, at the top of the stack. * It uses Animated.timing() by default, if you want to use another animation type, see `animationIn`. * * Note: only `easing` and `duration` are needed. * * @default { easing: Easing.inOut(Easing.exp), duration: 450 } * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#animateinconfig */ animateInConfig?: Pick<Animated.TimingAnimationConfig, 'duration' | 'easing'> /** * Animation function that receives the `animatedValue` used by the library to animate the modal opening, * and a `toValue` argument representing the modal position in the stack. * * Note: If you just want to use Animated.timing(), check `animateInConfig`. * * @default - * @example * animationIn: (modalAnimatedValue, modalToValue) => { * Animated.parallel([ * Animated.timing(modalAnimatedValue, { * toValue: modalToValue, * duration: 300, * easing: Easing.inOut(Easing.exp), * useNativeDriver: true, * }), * Animated.timing(myOtherAnimatedValue, { * toValue: 1, * duration: 300, * easing: Easing.inOut(Easing.exp), * useNativeDriver: true, * }), * ]).start() * } * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#animationin */ animationIn?: ( animatedValue: Animated.Value, toValue: number, ) => Animated.CompositeAnimation | void /** * Animation configuration used to animate a modal out (underneath other modals or when closing the last one). * Uses Animated.timing(), if you want to use another animation type, use `animationOut`. * * Note: only `easing` and `duration` are needed. * * @default { easing: Easing.inOut(Easing.exp), duration: 450 } * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#animationout */ animateOutConfig?: Pick<Animated.TimingAnimationConfig, 'duration' | 'easing'> /** * Animation function that receives the `animatedValue` used by the library to animate the modal closing, * and a `toValue` argument representing the modal position in the stack. * * Note: If you just want to use Animated.timing(), check `animateOutConfig`. * * @default - * @example * animationOut: (modalAnimatedValue, modalToValue) => { * Animated.parallel([ * Animated.timing(modalAnimatedValue, { * toValue: modalToValue, * duration: 300, * easing: Easing.inOut(Easing.exp), * useNativeDriver: true, * }), * Animated.timing(myOtherAnimatedValue, { * toValue: 1, * duration: 300, * easing: Easing.inOut(Easing.exp), * useNativeDriver: true, * }), * ]).start() * } * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#animationout */ animationOut?: ( animatedValue: Animated.Value, toValue: number, ) => Animated.CompositeAnimation | void /** * How you want the modal stack to behave when users press the backdrop, but also when the physical back button is pressed on Android. * * @default 'pop' * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#backbehavior */ backBehavior?: 'clear' | 'pop' | 'none' /** * Color of the modal stack backdrop. * * @default 'black' * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#backdropcolor */ backdropColor?: ViewStyle['backgroundColor'] /** * Number between `0` and `1` that defines the backdrop opacity. * * @default 0.6 * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#backdropopacity */ backdropOpacity?: number /** * Styles applied to the `<View>` directly wrapping your modal component. * * @default '{}' * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#containerstyle */ containerStyle?: ViewStyle /** * Disable fling gesture detection to close the modal. * * Note: the fling gesture handler is not enabled when `position` is `center`. * * @default false * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#disableflinggesture */ disableFlingGesture?: boolean /** * React component that will be rendered when you'll open the modal. * * Note: only needed when you're using this inside createModalStack() 1st argument. * * @default - * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#modal */ modal?: ComponentType<any> /** * Vertical positioning of the modal. * * @default 'center' * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#position */ position?: 'center' | 'top' | 'bottom' /** * Should closing a modal be animated. * * @deprecated since v2.0 | Use `animateConfigOut` instead. * @default false */ shouldAnimateOut?: boolean /** * `transitionOptions(animatedValue)` returns a React Native style object containing values that can use the provided `animatedValue` to run animation interpolations on a modal. * * Note: the object returned by `transitionOptions()` must contain keys that work with `useNativeDriver: true`. * * @default - * @see https://colorfy-software.gitbook.io/react-native-modalfy/api/types/modaloptions#transitionoptions */ transitionOptions?: ModalTransitionOptions } /** * Interface of the `modal` prop exposed by the library to regular components. * * @argument { unknown } ModalStackParamsList? - Interface of the whole modal stack params. * @argument { unknown } Props? - Component's props interface. * * Note: Modal components used in `createModalStack()`'s config should employ `ModalComponentProp` instead. * * @see https://colorfy-software.gitbook.io/react-native-modalfy/guides/typing#modalprop */ export type ModalProp<P extends ModalfyParams, Props = unknown> = Props & { /** * Interface of the `modal` prop exposed by the library to regular components. * * Note: Modal components used in `createModalStack()`'s config should employ `ModalComponentProp` instead. * * @see https://colorfy-software.gitbook.io/react-native-modalfy/guides/typing#modalprop */ modal: UsableModalProp<P> } /** * Interface of the `modal` prop exposed by the library specifically to modal components. * * @argument { unknown } ModalStackParamsList? - Interface of the whole modal stack params. * @argument { unknown } Props? - Component's props interface. * @argument { string } ModalName? - Name of the current modal * * Note: Components that are not used from `createModalStack()`'s config should employ `ModalProp` instead. * * @see https://colorfy-software.gitbook.io/react-native-modalfy/guides/typing#modalcomponentprop */ export type ModalComponentProp< P extends ModalfyParams, Props = unknown, M extends keyof P = keyof P > = Props & { /** * Interface of the `modal` prop exposed by the library specifically to modal components. * * Note: Components that are not used from `createModalStack()`'s config should employ `ModalProp` instead. * * @see https://colorfy-software.gitbook.io/react-native-modalfy/guides/typing#modalcomponentprop */ modal: UsableModalComponentProp<P, M> } /** * Interface for a React component containing its props and the `modalOptions` static property. * * Note: Only use with Hooks modal components (those present in your `createModalStack()`'s config). * If you're working with a Class modal component, you can directly use `static modalOptions: ModalOptions`. * * @argument { unknown } Props? - Component's props interface. * * @see https://colorfy-software.gitbook.io/react-native-modalfy/guides/typing#modalcomponentwithoptions */ export type ModalComponentWithOptions<P = unknown> = ComponentType<P> & { modalOptions?: ModalOptions }
the_stack
import * as msRest from "@azure/ms-rest-js"; import { ErrorRequestHandler, NextFunction, Request, RequestHandler, Response } from "express"; import ILogger from "../../common/ILogger"; import BlobStorageContext from "../context/BlobStorageContext"; import StorageErrorFactory from "../errors/StorageErrorFactory"; import * as Mappers from "../generated/artifacts/mappers"; import Specifications from "../generated/artifacts/specifications"; import MiddlewareError from "../generated/errors/MiddlewareError"; import IBlobMetadataStore from "../persistence/IBlobMetadataStore"; import { DEFAULT_CONTEXT_PATH, HeaderConstants, MethodConstants } from "../utils/constants"; export default class PreflightMiddlewareFactory { constructor(private readonly logger: ILogger) {} public createOptionsHandlerMiddleware( metadataStore: IBlobMetadataStore ): ErrorRequestHandler { return ( err: MiddlewareError | Error, req: Request, res: Response, next: NextFunction ) => { if (req.method.toUpperCase() === MethodConstants.OPTIONS) { const context = new BlobStorageContext( res.locals, DEFAULT_CONTEXT_PATH ); const requestId = context.contextId; const account = context.account!; this.logger.info( `PreflightMiddlewareFactory.createOptionsHandlerMiddleware(): OPTIONS request.`, requestId ); const origin = req.header(HeaderConstants.ORIGIN); if (origin === undefined || typeof origin !== "string") { return next( StorageErrorFactory.getInvalidCorsHeaderValue(requestId, { MessageDetails: `Invalid required CORS header Origin ${JSON.stringify( origin )}` }) ); } const requestMethod = req.header( HeaderConstants.ACCESS_CONTROL_REQUEST_METHOD ); if (requestMethod === undefined || typeof requestMethod !== "string") { return next( StorageErrorFactory.getInvalidCorsHeaderValue(requestId, { MessageDetails: `Invalid required CORS header Access-Control-Request-Method ${JSON.stringify( requestMethod )}` }) ); } const requestHeaders = req.headers[ HeaderConstants.ACCESS_CONTROL_REQUEST_HEADERS ] as string; metadataStore .getServiceProperties(context, account) .then(properties => { if (properties === undefined || properties.cors === undefined) { return next( StorageErrorFactory.corsPreflightFailure(requestId, { MessageDetails: "No CORS rules matches this request" }) ); } const corsSet = properties.cors; for (const cors of corsSet) { if ( !this.checkOrigin(origin, cors.allowedOrigins) || !this.checkMethod(requestMethod, cors.allowedMethods) ) { continue; } if ( requestHeaders !== undefined && !this.checkHeaders(requestHeaders, cors.allowedHeaders || "") ) { continue; } res.setHeader( HeaderConstants.ACCESS_CONTROL_ALLOW_ORIGIN, origin ); res.setHeader( HeaderConstants.ACCESS_CONTROL_ALLOW_METHODS, requestMethod ); if (requestHeaders !== undefined) { res.setHeader( HeaderConstants.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders ); } res.setHeader( HeaderConstants.ACCESS_CONTROL_MAX_AGE, cors.maxAgeInSeconds ); res.setHeader( HeaderConstants.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true" ); return next(); } return next( StorageErrorFactory.corsPreflightFailure(requestId, { MessageDetails: "No CORS rules matches this request" }) ); }) .catch(next); } else { next(err); } }; } public createCorsRequestMiddleware( metadataStore: IBlobMetadataStore, blockErrorRequest: boolean = false ): ErrorRequestHandler | RequestHandler { const internalMethod = ( err: MiddlewareError | Error | undefined, req: Request, res: Response, next: NextFunction ) => { if (req.method.toUpperCase() === MethodConstants.OPTIONS) { return next(err); } const context = new BlobStorageContext(res.locals, DEFAULT_CONTEXT_PATH); const account = context.account!; const origin = req.headers[HeaderConstants.ORIGIN] as string | undefined; if (origin === undefined) { return next(err); } const method = req.method; if (method === undefined || typeof method !== "string") { return next(err); } metadataStore .getServiceProperties(context, account) .then(properties => { if (properties === undefined || properties.cors === undefined) { return next(err); } const corsSet = properties.cors; const resHeaders = this.getResponseHeaders( res, err instanceof MiddlewareError ? err : undefined ); // Here we will match CORS settings in order and select first matched CORS for (const cors of corsSet) { if ( this.checkOrigin(origin, cors.allowedOrigins) && this.checkMethod(method, cors.allowedMethods) ) { const exposedHeaders = this.getExposedHeaders( resHeaders, cors.exposedHeaders || "" ); res.setHeader( HeaderConstants.ACCESS_CONTROL_EXPOSE_HEADERS, exposedHeaders ); res.setHeader( HeaderConstants.ACCESS_CONTROL_ALLOW_ORIGIN, cors.allowedOrigins === "*" ? "*" : origin! // origin is not undefined as checked in checkOrigin() ); if (cors.allowedOrigins !== "*") { res.setHeader(HeaderConstants.VARY, "Origin"); res.setHeader( HeaderConstants.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true" ); } return next(err); } } if (corsSet.length > 0) { res.setHeader(HeaderConstants.VARY, "Origin"); } return next(err); }) .catch(next); }; if (blockErrorRequest) { return internalMethod; } else { return (req: Request, res: Response, next: NextFunction) => { internalMethod(undefined, req, res, next); }; } } private checkOrigin( origin: string | undefined, allowedOrigin: string ): boolean { if (allowedOrigin === "*") { return true; } if (origin === undefined) { return false; } const allowedOriginArray = allowedOrigin.split(","); for (const corsOrigin of allowedOriginArray) { if (origin.trim().toLowerCase() === corsOrigin.trim().toLowerCase()) { return true; } } return false; } private checkMethod(method: string, allowedMethod: string): boolean { const allowedMethodArray = allowedMethod.split(","); for (const corsMethod of allowedMethodArray) { if (method.trim().toLowerCase() === corsMethod.trim().toLowerCase()) { return true; } } return false; } private checkHeaders(headers: string, allowedHeaders: string): boolean { const headersArray = headers.split(","); const allowedHeadersArray = allowedHeaders.split(","); for (const header of headersArray) { let flag = false; const trimmedHeader = header.trim().toLowerCase(); for (const allowedHeader of allowedHeadersArray) { // TODO: Should remove the wrapping blank when set CORS through set properties for service. const trimmedAllowedHeader = allowedHeader.trim().toLowerCase(); if ( trimmedHeader === trimmedAllowedHeader || (trimmedAllowedHeader[trimmedAllowedHeader.length - 1] === "*" && trimmedHeader.startsWith( trimmedAllowedHeader.substr(0, trimmedAllowedHeader.length - 1) )) ) { flag = true; break; } } if (flag === false) { return false; } } return true; } private getResponseHeaders(res: Response, err?: MiddlewareError): string[] { const responseHeaderSet = []; const context = new BlobStorageContext(res.locals, DEFAULT_CONTEXT_PATH); const handlerResponse = context.handlerResponses; if (handlerResponse && context.operation) { const statusCodeInResponse: number = handlerResponse.statusCode; const spec = Specifications[context.operation]; const responseSpec = spec.responses[statusCodeInResponse]; if (!responseSpec) { throw new TypeError( `Request specification doesn't include provided response status code` ); } // Serialize headers const headerSerializer = new msRest.Serializer(Mappers); const headersMapper = responseSpec.headersMapper; if (headersMapper && headersMapper.type.name === "Composite") { const mappersForAllHeaders = headersMapper.type.modelProperties || {}; // Handle headerMapper one by one for (const key in mappersForAllHeaders) { if (mappersForAllHeaders.hasOwnProperty(key)) { const headerMapper = mappersForAllHeaders[key]; const headerName = headerMapper.serializedName; const headerValueOriginal = handlerResponse[key]; const headerValueSerialized = headerSerializer.serialize( headerMapper, headerValueOriginal ); // Handle collection of headers starting with same prefix, such as x-ms-meta prefix const headerCollectionPrefix = (headerMapper as msRest.DictionaryMapper) .headerCollectionPrefix; if ( headerCollectionPrefix !== undefined && headerValueOriginal !== undefined ) { for (const collectionHeaderPartialName in headerValueSerialized) { if ( headerValueSerialized.hasOwnProperty( collectionHeaderPartialName ) ) { const collectionHeaderValueSerialized = headerValueSerialized[collectionHeaderPartialName]; const collectionHeaderName = `${headerCollectionPrefix}${collectionHeaderPartialName}`; if ( collectionHeaderName && collectionHeaderValueSerialized !== undefined ) { responseHeaderSet.push(collectionHeaderName); } } } } else { if (headerName && headerValueSerialized !== undefined) { responseHeaderSet.push(headerName); } } } } } if ( spec.isXML && responseSpec.bodyMapper && responseSpec.bodyMapper.type.name !== "Stream" ) { responseHeaderSet.push("content-type"); responseHeaderSet.push("content-length"); } else if ( handlerResponse.body && responseSpec.bodyMapper && responseSpec.bodyMapper.type.name === "Stream" ) { responseHeaderSet.push("content-length"); } } const headers = res.getHeaders(); for (const header in headers) { if (typeof header === "string") { responseHeaderSet.push(header); } } if (err) { for (const key in err.headers) { if (err.headers.hasOwnProperty(key)) { responseHeaderSet.push(key); } } } // TODO: Should extract the header by some policy. // or apply a referred list indicates the related headers. responseHeaderSet.push("Date"); responseHeaderSet.push("Connection"); responseHeaderSet.push("Transfer-Encoding"); return responseHeaderSet; } private getExposedHeaders( responseHeaders: any, exposedHeaders: string ): string { const exposedHeaderRules = exposedHeaders.split(","); const prefixRules = []; const simpleHeaders = []; for (let i = 0; i < exposedHeaderRules.length; i++) { exposedHeaderRules[i] = exposedHeaderRules[i].trim(); if (exposedHeaderRules[i].endsWith("*")) { prefixRules.push( exposedHeaderRules[i] .substr(0, exposedHeaderRules[i].length - 1) .toLowerCase() ); } else { simpleHeaders.push(exposedHeaderRules[i]); } } const resExposedHeaders: string[] = []; for (const header of responseHeaders) { let isMatch = false; for (const rule of prefixRules) { if (header.toLowerCase().startsWith(rule)) { isMatch = true; break; } } if (!isMatch) { for (const simpleHeader of simpleHeaders) { if (header.toLowerCase() === simpleHeader.toLowerCase()) { isMatch = true; break; } } } if (isMatch) { resExposedHeaders.push(header); } } for (const simpleHeader of simpleHeaders) { let isMatch = false; for (const header of resExposedHeaders) { if (simpleHeader.toLowerCase() === header.toLowerCase()) { isMatch = true; break; } } if (!isMatch) { resExposedHeaders.push(simpleHeader); } } return resExposedHeaders.join(","); } }
the_stack
import * as ts from 'typescript'; import { AccessKind, getAccessKind, getBaseClassMemberOfClassElement, getInstanceTypeOfClassLikeDeclaration, getSymbolOfClassLikeDeclaration, hasModifier, isClassLikeDeclaration, isCompilerOptionEnabled, isFunctionScopeBoundary, isIntersectionType, isParameterDeclaration, isThisParameter, isTypeParameter, isTypeReference, } from 'tsutils'; export function getRestrictedElementAccessError( checker: ts.TypeChecker, symbol: ts.Symbol, name: string, node: ts.ElementAccessExpression, lhsType: ts.Type, compilerOptions: ts.CompilerOptions, ): string | undefined { const flags = getModifierFlagsOfSymbol(symbol); if (node.expression.kind === ts.SyntaxKind.ThisKeyword && hasNonPrototypeDeclaration(symbol)) { const useDuringClassInitialization = getPropertyDeclarationOrConstructorAccessingProperty(node.parent!); if (useDuringClassInitialization !== undefined) { if (flags & ts.ModifierFlags.Abstract) return `Abstract property '${name}' in class '${printClass(getSymbolOfClassLikeDeclaration(<ts.ClassLikeDeclaration>useDuringClassInitialization.parent, checker), checker)}' cannot be accessed during class initialization.`; if ( // checking use before assign in constructor requires control flow graph useDuringClassInitialization.kind !== ts.SyntaxKind.Constructor && // only checking read access getAccessKind(node) & AccessKind.Read && isPropertyUsedBeforeAssign(symbol.valueDeclaration!, useDuringClassInitialization, compilerOptions, checker) ) return `Property '${name}' is used before its initialization.`; } } if (node.expression.kind === ts.SyntaxKind.SuperKeyword && (flags & ts.ModifierFlags.Static) === 0 && !isStaticSuper(node)) { if (hasNonPrototypeDeclaration(symbol)) return "Only public and protected methods and accessors of the base class are accessible via the 'super' keyword."; if ( flags & ts.ModifierFlags.Abstract && symbol.declarations!.every((d) => hasModifier(d.modifiers, ts.SyntaxKind.AbstractKeyword)) ) return `Abstract member '${name}' in class '${printClass(getDeclaringClassOfMember(symbol.valueDeclaration!, checker), checker)}' cannot be accessed via the 'super' keyword.`; } if ((flags & ts.ModifierFlags.NonPublicAccessibilityModifier) === 0) return; if (flags & ts.ModifierFlags.Private) { const declaringClass = getDeclaringClassOfMember(symbol.valueDeclaration!, checker); if (node.pos < declaringClass.valueDeclaration!.pos || node.end > declaringClass.valueDeclaration!.end) return failVisibility(name, printClass(declaringClass, checker), true); } else { const declaringClasses = symbol.declarations!.map( (d) => <ts.ClassLikeDeclaration>getDeclaringClassOfMember(d, checker).valueDeclaration); let enclosingClass = findEnclosingClass(node.parent!, declaringClasses, checker); if (enclosingClass === undefined) { if ((flags & ts.ModifierFlags.Static) === 0) enclosingClass = getEnclosingClassFromThisParameter(node.parent!, declaringClasses, checker); if (enclosingClass === undefined) return failVisibility(name, checker.typeToString(lhsType), false); } if ((flags & ts.ModifierFlags.Static) === 0 && !hasBase(lhsType, enclosingClass, isIdentical)) return `Property '${name}' is protected and only accessible through an instance of class '${checker.typeToString(enclosingClass)}'.`; } return; } function failVisibility(property: string, typeString: string, isPrivate: boolean) { return `Property '${property}' is ${isPrivate ? 'private' : 'protected'} and only accessible within class '${typeString}'${isPrivate ? '' : ' and its subclasses'}.`; } function findEnclosingClass(node: ts.Node, baseClasses: ts.ClassLikeDeclaration[], checker: ts.TypeChecker) { while (true) { switch (node.kind) { case ts.SyntaxKind.ClassDeclaration: case ts.SyntaxKind.ClassExpression: { const declaredType = getInstanceTypeOfClassLikeDeclaration(<ts.ClassLikeDeclaration>node, checker); if (baseClasses.every((baseClass) => hasBase(declaredType, baseClass, typeContainsDeclaration))) return declaredType; break; } case ts.SyntaxKind.SourceFile: return; } node = node.parent!; } } function printClass(symbol: ts.Symbol, checker: ts.TypeChecker) { return checker.typeToString(checker.getDeclaredTypeOfSymbol(symbol)); } function getEnclosingClassFromThisParameter(node: ts.Node, baseClasses: ts.ClassLikeDeclaration[], checker: ts.TypeChecker) { const thisParameter = getThisParameterFromContext(node); if (thisParameter?.type === undefined) return; let thisType = checker.getTypeFromTypeNode(thisParameter.type); if (isTypeParameter(thisType)) { const constraint = thisType.getConstraint(); if (constraint === undefined) return; thisType = constraint; } if (isTypeReference(thisType)) thisType = thisType.target; return baseClasses.every((baseClass) => hasBase(thisType, baseClass, typeContainsDeclaration)) ? thisType : undefined; } function isStaticSuper(node: ts.Node) { while (true) { switch (node.kind) { // super in computed property names, heritage clauses and decorators refers to 'this' outside of the current class case ts.SyntaxKind.ComputedPropertyName: case ts.SyntaxKind.ExpressionWithTypeArguments: node = node.parent!.parent!.parent!; break; case ts.SyntaxKind.Decorator: switch (node.parent!.kind) { case ts.SyntaxKind.ClassDeclaration: case ts.SyntaxKind.ClassExpression: node = node.parent.parent!; break; case ts.SyntaxKind.Parameter: node = node.parent.parent!.parent!.parent!; break; default: // class element decorator node = node.parent.parent!.parent!; } break; case ts.SyntaxKind.PropertyDeclaration: case ts.SyntaxKind.MethodDeclaration: case ts.SyntaxKind.GetAccessor: case ts.SyntaxKind.SetAccessor: return hasModifier(node.modifiers, ts.SyntaxKind.StaticKeyword); case ts.SyntaxKind.Constructor: return false; default: node = node.parent!; } } } function hasNonPrototypeDeclaration(symbol: ts.Symbol) { for (const {kind} of symbol.declarations!) { switch (kind) { case ts.SyntaxKind.MethodDeclaration: case ts.SyntaxKind.MethodSignature: case ts.SyntaxKind.GetAccessor: case ts.SyntaxKind.SetAccessor: continue; } return true; } return false; } function getPropertyDeclarationOrConstructorAccessingProperty(node: ts.Node) { while (true) { if (isFunctionScopeBoundary(node)) return node.kind === ts.SyntaxKind.Constructor ? <ts.ConstructorDeclaration>node : undefined; if (node.kind === ts.SyntaxKind.PropertyDeclaration) return <ts.PropertyDeclaration>node; node = node.parent!; } } function hasBase<T>(type: ts.Type, needle: T, check: (type: ts.Type, needle: T) => boolean) { return (function recur(t): boolean { if (isTypeReference(t)) { t = t.target; if (check(t, needle)) return true; } if (t.getBaseTypes()?.some(recur)) return true; return isIntersectionType(t) && t.types.some(recur); })(type); } function isIdentical<T>(a: T, b: T) { return a === b; } function typeContainsDeclaration(type: ts.Type, declaration: ts.Declaration) { return type.symbol!.declarations!.includes(declaration); } function getThisParameterFromContext(node: ts.Node) { while (true) { switch (node.kind) { case ts.SyntaxKind.FunctionDeclaration: case ts.SyntaxKind.FunctionExpression: case ts.SyntaxKind.MethodDeclaration: { const {parameters} = <ts.FunctionLikeDeclaration>node; return parameters.length !== 0 && isThisParameter(parameters[0]) ? parameters[0] : undefined; } case ts.SyntaxKind.ClassDeclaration: case ts.SyntaxKind.ClassExpression: case ts.SyntaxKind.SetAccessor: case ts.SyntaxKind.GetAccessor: case ts.SyntaxKind.EnumDeclaration: case ts.SyntaxKind.SourceFile: return; // this in computed property names, heritage clauses and decorators refers to 'super' outside of the current class case ts.SyntaxKind.ComputedPropertyName: case ts.SyntaxKind.ExpressionWithTypeArguments: node = node.parent!.parent!.parent!; break; case ts.SyntaxKind.Decorator: switch (node.parent!.kind) { case ts.SyntaxKind.ClassDeclaration: case ts.SyntaxKind.ClassExpression: node = node.parent.parent!; break; case ts.SyntaxKind.Parameter: node = node.parent.parent!.parent!.parent!; break; default: // class element decorator node = node.parent.parent!.parent!; } break; default: node = node.parent!; } } } function getModifierFlagsOfSymbol(symbol: ts.Symbol): ts.ModifierFlags { return symbol.declarations === undefined ? ts.ModifierFlags.None : symbol.declarations.reduce((flags, decl) => flags | ts.getCombinedModifierFlags(decl), ts.ModifierFlags.None); } function isPropertyUsedBeforeAssign( prop: ts.Declaration, usedIn: ts.PropertyDeclaration, compilerOptions: ts.CompilerOptions, checker: ts.TypeChecker, ): boolean { if (isParameterDeclaration(prop)) // when emitting native class fields, parameter properties cannot be used in other property's initializers in the same class return prop.parent!.parent === usedIn.parent && isEmittingNativeClassFields(compilerOptions); // this also matches assignment declarations in the same class; we could handle them, but TypeScript doesn't, so why bother if (prop.parent !== usedIn.parent) return false; // property is declared before use in the same class if (prop.pos < usedIn.pos) { // OK if immediately initialized if ((<ts.PropertyDeclaration>prop).initializer !== undefined || (<ts.PropertyDeclaration>prop).exclamationToken !== undefined) return false; // NOT OK if [[Define]] semantics are used, because it overrides the property from the base class if ( !hasModifier(prop.modifiers, ts.SyntaxKind.DeclareKeyword) && isCompilerOptionEnabled(compilerOptions, 'useDefineForClassFields') ) return true; } return getBaseClassMemberOfClassElement(<ts.PropertyDeclaration>prop, checker) === undefined; } function isEmittingNativeClassFields(compilerOptions: ts.CompilerOptions) { return compilerOptions.target === ts.ScriptTarget.ESNext && isCompilerOptionEnabled(compilerOptions, 'useDefineForClassFields'); } function getDeclaringClassOfMember(node: ts.Node, checker: ts.TypeChecker): ts.Symbol { switch (node.kind) { case ts.SyntaxKind.PropertyDeclaration: // regular property return getSymbolOfClassLikeDeclaration(<ts.ClassLikeDeclaration>node.parent, checker); case ts.SyntaxKind.Parameter: // parameter property return getSymbolOfClassLikeDeclaration(<ts.ClassLikeDeclaration>node.parent!.parent, checker); case ts.SyntaxKind.MethodDeclaration: case ts.SyntaxKind.GetAccessor: case ts.SyntaxKind.SetAccessor: if (isClassLikeDeclaration(node.parent!)) return getSymbolOfClassLikeDeclaration(node.parent, checker); // falls through // JS special property assignment declarations case ts.SyntaxKind.PropertyAssignment: // 'C.prototype = {method() {}, prop: 1, shorthand, get a() {return 1;}, set a(v) {}} case ts.SyntaxKind.ShorthandPropertyAssignment: return checker.getSymbolAtLocation((<ts.AccessExpression>(<ts.BinaryExpression>node.parent!.parent).left).expression)!; case ts.SyntaxKind.BinaryExpression: // this.foo = 1; node = (<ts.BinaryExpression>node).left; // falls through case ts.SyntaxKind.PropertyAccessExpression: // 'this.foo', 'C.foo' or 'C.prototype.foo' case ts.SyntaxKind.ElementAccessExpression: node = (<ts.AccessExpression>node).expression; switch (node.kind) { case ts.SyntaxKind.PropertyAccessExpression: case ts.SyntaxKind.ElementAccessExpression: node = (<ts.AccessExpression>node).expression; } return checker.getSymbolAtLocation(node)!; /* istanbul ignore next */ default: throw new Error(`unhandled property declaration kind ${node.kind}`); // this doesn't handle access modifier: 'Object.defineProperty(C, 'foo', ...)' or 'Object.defineProperty(C.prototype, 'foo', ...)' } }
the_stack
import { SubscriptionServerOptions } from 'apollo-server-core' import { PlaygroundRenderPageOptions } from 'apollo-server-express' import { CorsOptions as OriginalCorsOption } from 'cors' import * as Setset from 'setset' import { LiteralUnion, Primitive } from 'type-fest' import * as Utils from '../../lib/utils' import { ApolloConfigEngine } from './apollo-server/types' import { log as serverLogger } from './logger' type ResolvedOptional<T> = Exclude<NonNullable<T>, Primitive> export type ServerSettingsManager = Setset.Manager<SettingsInput, SettingsData> export type HTTPMethods = LiteralUnion<'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD', string> export type PlaygroundLonghandInput = { /** * Should the [GraphQL Playground](https://github.com/prisma-labs/graphql-playground) be hosted by the server? * * @dynamicDefault * * - If not production then `true` * - Otherwise `false` * * @remarks * * GraphQL Playground is useful during development as a visual client to interact with your API. In * production, without some kind of security/access control, you will almost * certainly want it disabled. */ enabled?: boolean // todo consider de-nesting the settings field /** * Configure the settings of the GraphQL Playground app itself. */ settings?: Omit<Partial<Exclude<PlaygroundRenderPageOptions['settings'], undefined>>, 'general.betaUpdates'> } type SubscriptionsLonghandInput = Omit<SubscriptionServerOptions, 'path'> & { /** * The path for clients to send subscriptions to. * * @default "/graphql" */ path?: string /** * Disable or enable the subscriptions server. * * @dynamicDefault * * - true if there is a Subscription type in your schema * - false otherwise */ enabled?: boolean } export type SettingsInput = { /** * Configure the subscriptions server. * * - Pass true to force enable with setting defaults * - Pass false to force disable * - Pass settings to customize config. Note does not imply enabled. Set "enabled: true" for that or rely on default. * * @dynamicDefault * * - true if there is a Subscription type in your schema * - false otherwise */ subscriptions?: boolean | SubscriptionsLonghandInput /** * Port the server should be listening on. * * todo default */ port?: number /** * Host the server should be listening on. * * todo default */ host?: string | undefined /** * Configure the [GraphQL Playground](https://github.com/prisma-labs/graphql-playground) hosted by the server. * * - Pass `true` as shorthand for `{ enabled: true }` * - Pass `false` as shorthand for `{ enabled: false }` * - Pass an object to configure * * @dynamicDefault * * - If not production then `true` * - Otherwise `false` * * @remarks * * GraphQL Playground is useful during development as a visual client to interact with your API. In * production, without some kind of security/access control, you will almost * certainly want it disabled. */ playground?: boolean | PlaygroundLonghandInput /** * Enable CORS for your server * * When true is passed, the default config is the following: * * ``` * { * "origin": "*", * "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", * "preflightContinue": false, * "optionsSuccessStatus": 204 * } * ``` * * @default false */ cors?: | boolean | { /** * Enable or disable CORS. * * @default true */ enabled?: boolean /** * Configures the Access-Control-Allow-Origin CORS header. Possible values: * * Boolean - set origin to true to reflect the request origin, as defined by req.header('Origin'), or set it to false to disable CORS. * * String - set origin to a specific origin. For example if you set it to "http://example.com" only requests from "http://example.com" will be allowed. * * RegExp - set origin to a regular expression pattern which will be used to test the request origin. If it's a match, the request origin will be reflected. For example the pattern /example\.com$/ will reflect any request that is coming from an origin ending with "example.com". * * Array - set origin to an array of valid origins. Each origin can be a String or a RegExp. For example ["http://example1.com", /\.example2\.com$/] will accept any request from "http://example1.com" or from a subdomain of "example2.com". * * Function - set origin to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (called as callback(err, origin), where origin is a non-function value of the origin option) as the second. * */ origin?: OriginalCorsOption['origin'] // TODO: Improve function interface with promise-based callback /** * Configures the Access-Control-Allow-Methods CORS header. * * @example ['GET', 'PUT', 'POST'] */ methods?: string | HTTPMethods[] /** * Configures the Access-Control-Allow-Headers CORS header. * * If not specified, defaults to reflecting the headers specified in the request's Access-Control-Request-Headers header. * * @example ['Content-Type', 'Authorization'] */ allowedHeaders?: string | string[] /** * Configures the Access-Control-Expose-Headers CORS header. * * If not specified, no custom headers are exposed. * * @example ['Content-Range', 'X-Content-Range'] */ exposedHeaders?: string | string[] /** * Configures the Access-Control-Allow-Credentials CORS header. * * Set to true to pass the header, otherwise it is omitted. */ credentials?: boolean /** * Configures the Access-Control-Max-Age CORS header. * * Set to an integer to pass the header, otherwise it is omitted. */ maxAge?: number /** * Pass the CORS preflight response to the next handler. */ preflightContinue?: boolean /** * Provides a status code to use for successful OPTIONS requests, since some legacy browsers (IE11, various SmartTVs) choke on 204. */ optionsSuccessStatus?: number } /** * The path on which the GraphQL API should be served. * * @default /graphql */ path?: string /** * Settings that are particualr to [Apollo](https://www.apollographql.com/). * * @remarks * * Under the hood Nexus' server implementation is powered by Apollo Server. You will not find all Apollo Server options here however. Only the ones that are particular to Apollo. Nexus does not consider generic server setting areas like CORS and GraphQL Playground as being Apollo settings. */ apollo?: { /** * The so-called "Apollo Reporting Options". For details about them refer [its official documentation](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#enginereportingoptions). Many of the settings here are for Apollo Studio. You may also want to refer to its [official documentation](https://www.apollographql.com/docs/studio/schema/schema-reporting). * * - Pass false to disable * - Pass true to enable with defaults * - Pass an object of settings to customize the various options. This does not imply enabled. For that you must set "enabled: true". * * Some of these settings respond to special envars. * * - APOLLO_KEY -> apiKey * - APOLLO_GRAPH_VARIANT -> graphVariant * * @default false */ engine?: | boolean | (ApolloConfigEngine & { enabled?: boolean }) } /** * Create a message suitable for printing to the terminal about the server * having been booted. */ startMessage?: (startInfo: ServerStartInfo) => void /** * todo */ graphql?: { introspection?: boolean } } type ServerStartInfo = { port: number host: string ip: string paths: { graphql: string graphqlSubscriptions: null | string } } export type SettingsData = Setset.InferDataFromInput< Omit<SettingsInput, 'host' | 'cors' | 'apollo' | 'subscriptions'> > & { host?: string cors: ResolvedOptional<SettingsInput['cors']> subscriptions: Omit<SubscriptionsLonghandInput, 'enabled' | 'path'> & { enabled: boolean path: string } apollo: { engine: ApolloConfigEngine & { enabled: boolean } } } export const createServerSettingsManager = () => Setset.create<SettingsInput, SettingsData>({ fields: { subscriptions: { shorthand(enabled) { return { enabled } }, fields: { path: { initial() { return '/graphql' }, }, keepAlive: {}, onConnect: {}, onDisconnect: {}, enabled: { initial() { // This is not accurate. The default is actually dynamic depending // on if the user has defined any subscription type or not. return true }, }, }, }, apollo: { fields: { engine: { shorthand(enabled) { return { enabled } }, fields: { enabled: { initial() { return false }, }, }, }, }, }, playground: { shorthand(enabled) { return { enabled } }, fields: { enabled: { initial() { return process.env.NODE_ENV === 'production' ? false : true }, }, settings: { fields: { 'editor.cursorShape': { initial() { return 'block' }, }, 'editor.fontFamily': { initial() { return `'Source Code Pro', 'Consolas', 'Inconsolata', 'Droid Sans Mono', 'Monaco', monospace` }, }, 'editor.fontSize': { initial() { return 14 }, }, 'editor.reuseHeaders': { initial() { return true }, }, 'editor.theme': { initial() { return 'dark' }, }, 'queryPlan.hideQueryPlanResponse': { initial() { return true }, }, 'request.credentials': { initial() { return 'omit' }, }, 'tracing.hideTracingResponse': { initial() { return true }, }, }, }, }, }, cors: { shorthand(enabled) { return { enabled, exposedHeaders: [] } }, fields: { allowedHeaders: {}, credentials: {}, enabled: {}, exposedHeaders: {}, maxAge: {}, methods: {}, optionsSuccessStatus: {}, origin: {}, preflightContinue: {}, }, }, graphql: { fields: { introspection: { initial() { return process.env.NODE_ENV === 'production' ? false : true }, }, }, }, host: { initial() { return process.env.NEXUS_HOST ?? process.env.HOST ?? undefined }, }, path: { initial() { return '/graphql' }, validate(value) { if (value.length === 0) { return { reasons: ['Custom GraphQL `path` cannot be empty and must start with a /'] } } return null }, fixup(value) { const messages: string[] = [] if (!value.startsWith('/')) { messages.push('Custom GraphQL `path` must start with a "/". Please add it.') value = '/' + value } return messages.length ? { value, messages } : null }, }, port: { initial() { return typeof process.env.NEXUS_PORT === 'string' ? parseInt(process.env.NEXUS_PORT, 10) : typeof process.env.PORT === 'string' ? // e.g. Heroku convention https://stackoverflow.com/questions/28706180/setting-the-port-for-node-js-server-on-heroku parseInt(process.env.PORT, 10) : process.env.NODE_ENV === 'production' ? 80 : 4000 }, }, startMessage: { initial() { return ({ port, host, paths }): void => { const url = `http://${Utils.prettifyHost(host)}:${port}${paths.graphql}` const subscriptionsURL = paths.graphqlSubscriptions ? `http://${Utils.prettifyHost(host)}:${port}${paths.graphqlSubscriptions}` : null serverLogger.info('listening', { url, subscriptionsURL, }) } }, }, }, })
the_stack
import sinon from 'sinon' import { Env } from '../../global/env' import { Dom } from '../dom' import { Hook } from './hook' describe('Dom', () => { describe('attributes', () => { describe('attr()', () => { it('should set attribute by key-value', () => { const div = new Dom('div') div.attr('tabIndex', 1) div.attr('aria-atomic', 'foo') expect(div.attr('tabIndex')).toEqual(1) expect(div.attr('aria-atomic')).toEqual('foo' as any) expect(div.attr('ariaAtomic')).toEqual('foo') }) it('should not process custom attribute name', () => { const div = new Dom('div') div.attr('fooBar', 'barz') expect(div.attr('fooBar')).toEqual('barz') expect(div.attr('foo-bar')).toBeUndefined() }) it('should be case-insensitive for HTMLElement attribute name', () => { const div = new Dom('div') div.attr('fooBar', 'barz') div.attr('tabIndex', 10) expect(div.attr('fooBar')).toEqual('barz') expect(div.attr('foobar')).toEqual('barz') expect(div.attr('Foobar')).toEqual('barz') expect(div.attr('tabIndex')).toEqual(10) expect(div.attr('tabindex')).toEqual(10) }) it('should remove attribute when the attribute value is null', () => { const div = new Dom('div') div.attr('fooBar', 'barz') div.attr('tabIndex', 10) expect(div.attr('fooBar')).toEqual('barz') expect(div.attr('tabIndex')).toEqual(10) div.attr('fooBar', null) div.attr('tabIndex', null) expect(div.attr('fooBar')).toBeUndefined() expect(div.attr('tabIndex')).toBeUndefined() }) it('should get all attributes', () => { const div = new Dom('div') div.attr('fooBar', 'barz') div.attr('tabIndex', 10) const ret = div.attr() as any // attribute name was convert to lowercase expect(ret.foobar).toEqual('barz') // special attribute name expect(ret.tabIndex).toEqual(10) // unspecified attribute expect(ret.left).toEqual(undefined) expect(Object.keys(ret).length).toEqual(2) }) it('should get specified attributes by name', () => { const div = new Dom('div') div.attr('fooBar', 'barz') div.attr('tabIndex', 10) const ret = div.attr(['fooBar', 'tabIndex']) // custom attribute name was keeped expect(ret.fooBar).toEqual('barz') expect(ret.tabIndex).toEqual(10) }) it('should convert boolean string to boolean', () => { const div = new Dom('div') div.attr('foo', 'true') div.attr('bar', 'false') div.attr('barz', 'xxx') expect(div.attr('foo')).toBeTrue() expect(div.attr('bar')).toBeFalse() expect(div.attr('barz')).toEqual('xxx') }) it('should convert numeric string to number', () => { const div = new Dom('div') div.attr('foo', '1') div.attr('bar', '-1') div.attr('barz', '1.5') expect(div.attr('foo')).toEqual(1) expect(div.attr('bar')).toEqual(-1) expect(div.attr('barz')).toEqual(1.5) }) it('should set/get special NUMERIC attributes', () => { const div = new Dom('div') div.attr('tabIndex', '1') div.attr('rowSpan', '-1') div.attr('colSpan', '2') div.attr('start', '1.5') expect(div.attr('tabIndex')).toEqual(1) expect(div.attr('rowSpan')).toEqual(-1) expect(div.attr('colSpan')).toEqual(2) expect(div.attr('start')).toEqual(1.5) }) it('should remove invalid value for NUMERIC attribute', () => { const div = new Dom('div') div.attr('tabIndex', '1') expect(div.attr('tabIndex')).toEqual(1) div.attr('tabIndex', 'a') expect(div.attr('tabIndex')).toBeUndefined() }) it('should set/get special POSITIVE_NUMERIC attributes', () => { const div = new Dom('div') div.attr('cols', 1) div.attr('rows', 2) div.attr('size', 3) div.attr('span', 4) expect(div.attr('cols')).toEqual(1) expect(div.attr('rows')).toEqual(2) expect(div.attr('size')).toEqual(3) expect(div.attr('span')).toEqual(4) }) it('should remove invalid value for POSITIVE_NUMERIC attribute', () => { const div = new Dom('div') div.attr('cols', 1) expect(div.attr('cols')).toEqual(1) div.attr('cols', -1) expect(div.attr('cols')).toBeUndefined() }) it('should set/get special BOOLEAN attributes', () => { const div = new Dom('div') div.attr('autoFocus', true) div.attr('async', 'true') expect(div.attr('autoFocus')).toEqual(true) expect(div.attr('async')).toEqual(true) }) it('should remove invalid value for BOOLEAN attribute', () => { const div = new Dom('div') div.attr('autoFocus', true) expect(div.attr('autoFocus')).toEqual(true) div.attr('autoFocus', 1) expect(div.attr('autoFocus')).toEqual(false) }) it('should convert inline BOOLEAN attributes', () => { const div = new Dom('div') div.node.setAttribute('autoFocus', 'true') expect(div.attr('autoFocus')).toEqual(true) div.node.setAttribute('autoFocus', 'false') expect(div.attr('autoFocus')).toEqual(false) }) it('should set/get special OVERLOADED_BOOLEAN attributes', () => { const div = new Dom('div') div.attr('capture', true) expect(div.attr('capture')).toEqual(true) div.attr('capture', 'demo') expect(div.attr('capture')).toEqual('demo') }) it('should convert inline OVERLOADED_BOOLEAN attributes', () => { const div = new Dom('div') div.node.setAttribute('capture', 'true') expect(div.attr('capture')).toEqual(true) div.node.setAttribute('capture', 'false') expect(div.attr('capture')).toEqual(false) div.node.setAttribute('capture', 'demo') expect(div.attr('capture')).toEqual('demo') }) it('should remove invalid value for OVERLOADED_BOOLEAN attribute', () => { const div = new Dom('div') div.attr('capture', true) expect(div.attr('capture')).toEqual(true) div.attr('capture', 'demo') expect(div.attr('capture')).toEqual('demo') div.attr('capture', false) expect(div.attr('capture')).toEqual(false) }) it('should set/get attributes store on properties', () => { const div = new Dom('div') div.attr('checked', true) expect(div.attr('checked')).toEqual(true) div.attr('checked', false) expect(div.attr('checked')).toEqual(false) div.attr('checked', true) expect(div.attr('checked')).toEqual(true) div.attr('checked', null) expect(div.attr('checked')).toEqual(false) }) it('should set/get special BOOLEANISH_STRING attributes', () => { const div = new Dom('div') expect(div.attr('draggable')).toEqual(false) div.attr('draggable', true) expect(div.attr('draggable')).toEqual(true) div.attr('draggable', 'false') expect(div.attr('draggable')).toEqual(false) }) it('should return style object', () => { const div = new Dom('div') div.css('left', 10) const style = div.attr('style') expect(style).toBeInstanceOf(Object) expect(style.left).toEqual('10px') }) it('should set style object', () => { const div = new Dom('div') div.attr('style', { left: 10 }) expect(div.css('left')).toEqual('10px') }) it('should set style string', () => { const div = new Dom('div') div.attr('style', 'left: 10px') expect(div.css('left')).toEqual('10px') }) it('should sanitize url', () => { const div = new Dom('div') div.attr('src', 'http://www.a.com') expect(div.attr('src')).toEqual('http://www.a.com') const spy = sinon.spy(console, 'error') const env = Env as any const old = env.isDev env.isDev = true // eslint-disable-next-line no-script-url div.attr('src', 'javascript:;') expect(spy.callCount).toEqual(1) env.isDev = old spy.restore() }) it('should auto set attribute with namespace', () => { const svg = new Dom('svg') svg.attr('xmlLang', 'foo') expect(svg.attr('xmlLang')).toEqual('foo') }) it('should remove attribute with function value', () => { const div = new Dom('div') div.attr('foo', 'bar') expect(div.attr('foo')).toEqual('bar') div.attr('foo', (() => {}) as any) expect(div.attr('foo')).toBeUndefined() }) it('should remove attribute when not accept boolean values', () => { const div = new Dom('div') div.attr('tabIndex', '1') expect(div.attr('tabIndex')).toEqual(1) div.attr('tabIndex', false) expect(div.attr('tabIndex')).toBeUndefined() }) it('should log error message when attribute not accept empty string', () => { const div = new Dom('div') div.attr('src', 'http://www.a.com') expect(div.attr('src')).toEqual('http://www.a.com') const spy = sinon.spy(console, 'error') const env = Env as any const old = env.isDev env.isDev = true div.attr('src', '') expect(div.attr('src')).toBeUndefined() expect(spy.callCount).toEqual(1) div.attr('action', 'foo') expect(div.attr('action')).toEqual('foo') div.attr('action', '') expect(div.attr('action')).toBeUndefined() expect(spy.callCount).toEqual(2) env.isDev = old spy.restore() }) it('should log error message when the attribute name is illegal', () => { const spy = sinon.spy(console, 'error') const env = Env as any const old = env.isDev env.isDev = true const div = new Dom('div') div.attr('1', '2') expect(spy.callCount).toEqual(1) div.attr('1', 2) // do not warn again expect(spy.callCount).toEqual(1) env.isDev = old spy.restore() }) it('should call get-hook', () => { const div = new Dom('div') Hook.register('foo', { get() { return 10 }, }) expect(div.attr('foo')).toEqual(10) div.attr('foo', 100) expect(div.attr('foo')).toEqual(10) Hook.unregister('foo') }) it('should call set-hook', () => { const div = new Dom('div') Hook.register('foo', { set(node, value) { if (typeof value === 'number') { node.setAttribute('foo', value > 0 ? '1' : '-1') return false } return value }, }) div.attr('foo', 'bar') expect(div.attr('foo')).toEqual('bar') div.attr('foo', 10) expect(div.attr('foo')).toEqual(1) div.attr('foo', -10) expect(div.attr('foo')).toEqual(-1) Hook.unregister('foo') }) }) describe('round()', () => { it('should round the specified numeric values', () => { const svg = new Dom('svg') svg.attr({ x: 1.33333333, y: 1.66666666, foo: 'bar', }) svg.round(2, ['x', 'foo'] as any) expect(svg.attr('x')).toEqual(1.33) expect(svg.attr('y')).toEqual(1.66666666) expect(svg.attr('foo')).toEqual('bar') }) it('should round all the numeric values', () => { const svg = new Dom('svg') svg.attr({ x: 1.33333333, y: 1.66666666, foo: 'bar', }) svg.round(2) expect(svg.attr('x')).toEqual(1.33) expect(svg.attr('y')).toEqual(1.67) expect(svg.attr('foo')).toEqual('bar') }) }) }) })
the_stack
import React, { useState, useEffect, useContext, useRef } from 'react'; import DeploymentCenterGitHubProvider from './DeploymentCenterGitHubProvider'; import { GitHubUser } from '../../../../models/github'; import { useTranslation } from 'react-i18next'; import DeploymentCenterData from '../DeploymentCenter.data'; import GitHubService from '../../../../ApiHelpers/GitHubService'; import { DeploymentCenterFieldProps, AuthorizationResult, SearchTermObserverInfo } from '../DeploymentCenter.types'; import { IDropdownOption } from 'office-ui-fabric-react'; import { DeploymentCenterContext } from '../DeploymentCenterContext'; import { authorizeWithProvider, getTelemetryInfo } from '../utility/DeploymentCenterUtility'; import { PortalContext } from '../../../../PortalContext'; import { KeyValue } from '../../../../models/portal-models'; import { Subject } from 'rxjs'; import { debounceTime, switchMap } from 'rxjs/operators'; const searchTermObserver = new Subject<SearchTermObserverInfo>(); searchTermObserver .pipe(debounceTime(500)) .pipe( switchMap(async info => { const searchTerm = info.searchTerm; const setRepositoryOptions = info.setRepositoryOptions; const setLoadingRepositories = info.setLoadingRepositories; const fetchBranchOptions = info.fetchBranchOptions; const deploymentCenterContext = info.deploymentCenterContext; const deploymentCenterData = info.deploymentCenterData; const portalContext = info.portalContext; const repositoriesUrl = info.repositoryUrl; const isGitHubActions = info.isGitHubActions; const org = info.org; const repo = info.repo; let gitHubRepositories; if (repositoriesUrl.toLocaleLowerCase().indexOf('github.com/users/') > -1) { gitHubRepositories = await deploymentCenterData.getGitHubUserRepositories( deploymentCenterContext.gitHubToken, (page, response) => { portalContext.log( getTelemetryInfo('error', 'getGitHubUserRepositoriesResponse', 'failed', { page, errorAsString: response && response.metadata && response.metadata.error && JSON.stringify(response.metadata.error), }) ); }, searchTerm ); } else { gitHubRepositories = await deploymentCenterData.getGitHubOrgRepositories( org, deploymentCenterContext.gitHubToken, (page, response) => { portalContext.log( getTelemetryInfo('error', 'getGitHubOrgRepositoriesResponse', 'failed', { page, errorAsString: response && response.metadata && response.metadata.error && JSON.stringify(response.metadata.error), }) ); }, searchTerm ); } let newRepositoryOptions: IDropdownOption[] = []; if (isGitHubActions) { newRepositoryOptions = gitHubRepositories.map(repo => ({ key: repo.name, text: repo.name })); } else { newRepositoryOptions = gitHubRepositories .filter(repo => !repo.permissions || repo.permissions.admin) .map(repo => ({ key: repo.name, text: repo.name })); } newRepositoryOptions.sort((a, b) => a.text.localeCompare(b.text)); setRepositoryOptions(newRepositoryOptions); setLoadingRepositories(false); // If the form props already contains selected data, set the default to that value. if (org && repo && repo == searchTerm) { await fetchBranchOptions(org, repo); } }) ) .subscribe(); const DeploymentCenterGitHubDataLoader: React.FC<DeploymentCenterFieldProps> = props => { const { t } = useTranslation(); const { formProps, isGitHubActions } = props; const deploymentCenterData = new DeploymentCenterData(); const deploymentCenterContext = useContext(DeploymentCenterContext); const portalContext = useContext(PortalContext); const [gitHubUser, setGitHubUser] = useState<GitHubUser | undefined>(undefined); const [gitHubAccountStatusMessage, setGitHubAccountStatusMessage] = useState<string | undefined>( t('deploymentCenterOAuthFetchingUserInformation') ); const [organizationOptions, setOrganizationOptions] = useState<IDropdownOption[]>([]); const [repositoryOptions, setRepositoryOptions] = useState<IDropdownOption[]>([]); const [branchOptions, setBranchOptions] = useState<IDropdownOption[]>([]); const [loadingOrganizations, setLoadingOrganizations] = useState(true); const [loadingRepositories, setLoadingRepositories] = useState(true); const [loadingBranches, setLoadingBranches] = useState(true); const [hasDeprecatedToken, setHasDeprecatedToken] = useState(false); const [updateTokenSuccess, setUpdateTokenSuccess] = useState(false); const [clearComboBox, setClearComboBox] = useState<KeyValue<boolean>>({ repo: true, branch: true }); const gitHubOrgToUrlMapping = useRef<{ [key: string]: string }>({}); const fetchOrganizationOptions = async () => { setLoadingOrganizations(true); gitHubOrgToUrlMapping.current = {}; setOrganizationOptions([]); setRepositoryOptions([]); setBranchOptions([]); const newOrganizationOptions: IDropdownOption[] = []; if (gitHubUser) { portalContext.log(getTelemetryInfo('info', 'getGitHubOrganizations', 'submit')); const gitHubOrganizations = await deploymentCenterData.getGitHubOrganizations( deploymentCenterContext.gitHubToken, (page, response) => { portalContext.log( getTelemetryInfo('error', 'getGitHubUserRepositoriesResponse', 'failed', { page, errorAsString: response && response.metadata && response.metadata.error && JSON.stringify(response.metadata.error), }) ); } ); gitHubOrganizations.forEach(org => { newOrganizationOptions.push({ key: org.login, text: org.login }); if (!gitHubOrgToUrlMapping.current[org.login]) { gitHubOrgToUrlMapping.current[org.login] = org.url; } }); newOrganizationOptions.push({ key: gitHubUser.login, text: gitHubUser.login }); if (!gitHubOrgToUrlMapping.current[gitHubUser.login]) { gitHubOrgToUrlMapping.current[gitHubUser.login] = gitHubUser.repos_url; } } setOrganizationOptions(newOrganizationOptions); setLoadingOrganizations(false); // If the form props already contains selected data, set the default to that value. if (formProps.values.org && gitHubOrgToUrlMapping.current[formProps.values.org]) { fetchRepositoryOptions(gitHubOrgToUrlMapping.current[formProps.values.org]); } }; const fetchRepositoryOptions = (repositoriesUrl: string, searchTerm?: string) => { setRepositoryOptions([]); setBranchOptions([]); portalContext.log(getTelemetryInfo('info', 'gitHubRepositories', 'submit')); const info: SearchTermObserverInfo = { searchTerm: searchTerm, setRepositoryOptions: setRepositoryOptions, setLoadingRepositories: setLoadingRepositories, fetchBranchOptions: fetchBranchOptions, repositoryUrl: repositoriesUrl, deploymentCenterData: deploymentCenterData, deploymentCenterContext: deploymentCenterContext, portalContext: portalContext, isGitHubActions: isGitHubActions, org: formProps.values.org, repo: formProps.values.repo, }; searchTermObserver.next(info); }; const fetchBranchOptions = async (org: string, repo: string) => { setLoadingBranches(true); setBranchOptions([]); const gitHubBranches = await deploymentCenterData.getGitHubBranches( org, repo, deploymentCenterContext.gitHubToken, (page, response) => { portalContext.log( getTelemetryInfo('error', 'getGitHubBranchesResponse', 'failed', { page, errorAsString: response && response.metadata && response.metadata.error && JSON.stringify(response.metadata.error), }) ); } ); const newBranchOptions: IDropdownOption[] = gitHubBranches.map(branch => ({ key: branch.name, text: branch.name })); setBranchOptions(newBranchOptions); setLoadingBranches(false); }; const authorizeGitHubAccount = () => { portalContext.log(getTelemetryInfo('info', 'gitHubAccount', 'authorize')); authorizeWithProvider(GitHubService.authorizeUrl, startingAuthCallback, completingAuthCallBack); }; const completingAuthCallBack = (authorizationResult: AuthorizationResult) => { if (authorizationResult.redirectUrl) { deploymentCenterData.getGitHubToken(authorizationResult.redirectUrl).then(response => { if (response.metadata.success) { deploymentCenterData.storeGitHubToken(response.data).then(() => deploymentCenterContext.refreshUserSourceControlTokens()); } else { portalContext.log( getTelemetryInfo('error', 'getGitHubTokenResponse', 'failed', { errorAsString: JSON.stringify(response.metadata.error), }) ); return Promise.resolve(undefined); } }); } else { return fetchData(); } }; const startingAuthCallback = (): void => { setGitHubAccountStatusMessage(t('deploymentCenterOAuthAuthorizingUser')); }; const resetToken = async () => { if (!!gitHubUser && !!deploymentCenterContext.gitHubToken) { const response = await deploymentCenterData.resetToken(deploymentCenterContext.gitHubToken); if (response.metadata.success) { deploymentCenterData.storeGitHubToken(response.data).then(() => { deploymentCenterContext.refreshUserSourceControlTokens(); setHasDeprecatedToken(false); setUpdateTokenSuccess(true); }); } else { portalContext.log( getTelemetryInfo('error', 'resetToken', 'failed', { errorAsString: JSON.stringify(response.metadata.error), }) ); } } }; // TODO(michinoy): We will need to add methods here to manage github specific network calls such as: // repos, orgs, branches, workflow file, etc. const fetchData = async () => { portalContext.log(getTelemetryInfo('info', 'getGitHubUser', 'submit')); const gitHubUserResponse = await deploymentCenterData.getGitHubUser(deploymentCenterContext.gitHubToken); setGitHubAccountStatusMessage(undefined); if (gitHubUserResponse.metadata.success && gitHubUserResponse.data.login) { // NOTE(michinoy): if unsuccessful, assume the user needs to authorize. setGitHubUser(gitHubUserResponse.data); formProps.setFieldValue('gitHubUser', gitHubUserResponse.data); } if (!!deploymentCenterContext.gitHubToken && !deploymentCenterContext.gitHubToken.startsWith('gho')) { portalContext.log( getTelemetryInfo('info', 'checkDeprecatedToken', 'submit', { resourceId: deploymentCenterContext.resourceId, }) ); setHasDeprecatedToken(true); } }; useEffect(() => { if (!formProps.values.gitHubUser) { fetchData(); } else { setGitHubUser(formProps.values.gitHubUser); setGitHubAccountStatusMessage(undefined); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [deploymentCenterContext.gitHubToken]); useEffect(() => { fetchOrganizationOptions(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [gitHubUser]); useEffect(() => { setBranchOptions([]); setClearComboBox({ branch: true, repo: true }); setLoadingRepositories(true); setLoadingBranches(true); if (formProps.values.org && gitHubOrgToUrlMapping.current[formProps.values.org]) { fetchRepositoryOptions(gitHubOrgToUrlMapping.current[formProps.values.org]); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [formProps.values.org]); useEffect(() => { setRepositoryOptions([]); setBranchOptions([]); setClearComboBox({ branch: true, repo: false }); setLoadingBranches(true); if ( formProps.values.org && gitHubOrgToUrlMapping.current[formProps.values.org] && formProps.values.org != formProps.values.searchTerm ) { fetchRepositoryOptions(gitHubOrgToUrlMapping.current[formProps.values.org], formProps.values.searchTerm); } }, [formProps.values.searchTerm]); useEffect(() => { setBranchOptions([]); setClearComboBox({ branch: true, repo: false }); setLoadingBranches(true); if (formProps.values.org && formProps.values.repo) { fetchBranchOptions(formProps.values.org, formProps.values.repo); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [formProps.values.repo]); return ( <DeploymentCenterGitHubProvider formProps={formProps} accountUser={gitHubUser} accountStatusMessage={gitHubAccountStatusMessage} authorizeAccount={authorizeGitHubAccount} organizationOptions={organizationOptions} repositoryOptions={repositoryOptions} branchOptions={branchOptions} loadingOrganizations={loadingOrganizations} loadingRepositories={loadingRepositories} loadingBranches={loadingBranches} hasDeprecatedToken={hasDeprecatedToken} updateTokenSuccess={updateTokenSuccess} resetToken={resetToken} clearComboBox={clearComboBox} /> ); }; export default DeploymentCenterGitHubDataLoader;
the_stack
import hash = require('object-hash'); import AWS = require('aws-sdk'); import moment = require('moment'); import { Handler, Context, Callback, ScheduledEvent } from 'aws-lambda'; import * as entities from '../../shared-lib/src/entities'; import * as wazeTypes from '../../shared-lib/src/waze-types'; import * as db from './db'; import util = require('util'); import { PromiseResult } from 'aws-sdk/lib/request'; import throttle = require('promise-parallel-throttle') import consolePatch from '../../shared-lib/src/consolePatch' const s3 = new AWS.S3(); const sqs = new AWS.SQS(); const lambda = new AWS.Lambda(); const sns = new AWS.SNS(); const throttleOpts:throttle.Options = { failFast: true, maxInProgress: parseInt(process.env.POOLSIZE) } //setup object hashing options once const hashOpts = { unorderedArrays: true }; const processDataFile: Handler = async (event: any, context: Context, callback: Callback) => { try{ //patch the console so we can get more searchable logging //would be nice to make this global, but couldn't quickly get that working consolePatch(); //we'll loop and process as long as there are records and the queue //and there is twice as much time left as the max loop time let isQueueDrained = false; let maxLoopTimeInMillis = 0; //keep this lambda alive and processing items from the queue as long as the time remaining //minus a 10 second buffer is greater than double the max iteration run time while(context.getRemainingTimeInMillis() - 10000 > maxLoopTimeInMillis * 2){ console.info('Continuing - Function time remaining: %d, Max iteration time: %d', context.getRemainingTimeInMillis(), maxLoopTimeInMillis); //"start" a timer for this iteration let loopStart = process.hrtime(); //attempt to grab a record from the queue let sqsParams: AWS.SQS.ReceiveMessageRequest = { QueueUrl: process.env.SQSURL, /* required */ MaxNumberOfMessages: 1, // we'll only do one at a time VisibilityTimeout: 330 // wait just a little longer than our 5 minute lambda timeout }; let sqsResponse = await sqs.receiveMessage(sqsParams).promise(); // make sure we got a record if(!sqsResponse.Messages || sqsResponse.Messages.length == 0){ //got no response, so set the flag and exit the loop isQueueDrained = true; break; } else { let s3Key = getS3KeyFromMessage(sqsResponse.Messages[0]); console.info("Retrieved S3 Key: %s", s3Key); // now need to read that file in let s3Params: AWS.S3.GetObjectRequest = { Bucket: process.env.WAZEDATAINCOMINGBUCKET, Key: s3Key, }; let s3Response = await s3.getObject(s3Params).promise(); //make sure we got something if(s3Response.Body){ let fileData: wazeTypes.dataFileWithInternalId = JSON.parse(s3Response.Body.toString()); //first need to see if we've seen this file before or not, based on hash //be sure to only compute the hash once, to save on processing let jsonHash = computeHash(fileData); let data_file = await db.getDataFilesByHashQuery(jsonHash); //if we got something, we need to check more stuff before updating anything if(data_file){ //see if the file name has changed, and if so throw an error if(data_file.file_name !== s3Key){ throw new Error(util.format("Found existing record for hash '%s' with file name '%s' (id: %d)", jsonHash, data_file.file_name, data_file.id)); } console.info(util.format('Updating data_file id: %d', data_file.id)); //no change to the name, so the only thing we need to do is update the date_updated field await db.updateDataFileUpdateDateByIdCommand(data_file.id); } else{ //we didn't get a record, so we need to save one //build up the object we'll (potentially) be inserting into the DB data_file = new entities.DataFile(); data_file.start_time_millis = fileData.startTimeMillis; data_file.end_time_millis = fileData.endTimeMillis; data_file.start_time = moment.utc(fileData.startTimeMillis).toDate(); data_file.end_time = moment.utc(fileData.endTimeMillis).toDate(); data_file.file_name = s3Key; data_file.json_hash = jsonHash; console.info(util.format('Creating data_file: %s', s3Key)); data_file = await db.insertDataFileCommand(data_file); } //now that we for sure have a data_file record in the DB, we'll need to pass the id on to everything else fileData.data_file_id = data_file.id; //split out each of the groups and send them off to their own parallel lambdas //it would be nice to also keep the root-level data intact, so we'll perform some trickery... //first get all 3 sets let alerts = fileData.alerts; let jams = fileData.jams; let irregularities = fileData.irregularities; //now delete all 3 from the root delete fileData.alerts; delete fileData.jams; delete fileData.irregularities; //we'll need to keep track of the promises to process let promises = new Array<Promise<PromiseResult<AWS.Lambda.InvocationResponse, AWS.AWSError>>>(); //now we can check if we have each one and send them off for processing if(alerts && alerts.length > 0){ //add the alerts back to the object fileData.alerts = alerts; console.info(util.format('Invoking alert processor with %d alerts', alerts.length)); //send it off to be processed promises.push(invokeListProcessor(fileData, process.env.ALERTPROCESSORARN)); //remove alerts from the object again delete fileData.alerts; } if(jams && jams.length > 0){ //add the jams back to the object fileData.jams = jams; console.info(util.format('Invoking jam processor with %d jams', jams.length)); //send it off to be processed promises.push(invokeListProcessor(fileData, process.env.JAMPROCESSORARN)); //remove jams from the object again delete fileData.jams; } if(irregularities && irregularities.length > 0){ //add the irregularities back to the object fileData.irregularities = irregularities; console.info(util.format('Invoking irregularity processor with %d irregularities', irregularities.length)); //send it off to be processed promises.push(invokeListProcessor(fileData, process.env.IRREGULARITYPROCESSORARN)); //remove irregularities from the object again delete fileData.irregularities; } //wait for all of the promises to finish if(promises.length > 0){ let promResult = await Promise.all(promises); let wereAllSuccessful = promResult.every(res => { //make sure we got a 200 and either have no FunctionError or an empty one return res.StatusCode == 200 && (!res.FunctionError || res.FunctionError.length == 0); }) //if they were NOT all successful, log an error with the whole response //most likely the individual processor that failed will have more info logged, //but this will at least get us *something* just in case if(!wereAllSuccessful) { console.error(promResult); callback(new Error('Error processing alerts/jams/irregularities, review logs for more info')); return; } //we got here, so everything appears to have processed successfully //if all processing completed, move file from inbound bucket to processed let copyObjParams: AWS.S3.CopyObjectRequest = { Bucket: process.env.WAZEDATAPROCESSEDBUCKET, Key: s3Key, CopySource: util.format('/%s/%s', process.env.WAZEDATAINCOMINGBUCKET, s3Key) } let s3CopyResponse = await s3.copyObject(copyObjParams).promise(); //make sure the copy didn't fail without throwing an error if(!s3CopyResponse.CopyObjectResult){ console.error(s3CopyResponse); callback(new Error('Error copying object to processed bucket: ' + s3Key)); return; } //now we can delete the file from the incoming bucket let deleteObjParams: AWS.S3.DeleteObjectRequest = { Bucket: process.env.WAZEDATAINCOMINGBUCKET, Key: s3Key } await s3.deleteObject(deleteObjParams).promise(); //if all processing completed, delete SQS message let deleteSqsParams: AWS.SQS.DeleteMessageRequest = { QueueUrl: process.env.SQSURL, ReceiptHandle: sqsResponse.Messages[0].ReceiptHandle } await sqs.deleteMessage(deleteSqsParams).promise(); //send a message to the SNS topic if enabled if(process.env.SNSTOPIC && process.env.SNSTOPIC.length > 0){ await publishSnsMessage('Successfully processed ' + s3Key, process.env.SNSTOPIC); } } } } //"stop" the timer let loopEnd = process.hrtime(loopStart); //convert loopend to milliseconds let loopTimeInMillis = (loopEnd["0"] * 1000) + (loopEnd["1"] / 1e6); //if this run was longer than the max, set a new max if(loopTimeInMillis > maxLoopTimeInMillis){ maxLoopTimeInMillis = loopTimeInMillis } } //if the queue is not drained, send a message to the SNS topic that retriggers this lambda if(!isQueueDrained){ //there's more in the queue, but we're low on time, so let's retrigger using sns await publishSnsMessage('Triggering self to continue work', process.env.RETRIGGERSNSTOPIC); } //nothing to return return; } catch (err) { console.error(err); callback(err); return err; } }; const processDataAlerts: Handler = async (event: wazeTypes.dataFileWithInternalId, context: Context, callback: Callback) => { try{ //patch the console so we can get more searchable logging //would be nice to make this global, but couldn't quickly get that working consolePatch(); //the event we get will actually already be JSON parsed into an object, no need to parse manually //get the startTimeMillis from the root of the file so we can use it later in our hashing let rootStart = event.startTimeMillis; //also grab the data_file_id let data_file_id = event.data_file_id; //create a list of tasks to process alerts _asynchronously_ let taskList = event.alerts.map((alert:wazeTypes.alert) => async () => { //hash the whole alert along with the rootStart to get a unique id let alertHash = generateAJIUniqueIdentifierHash(alert, rootStart); //build an alert object let alertEntity: entities.Alert = { id: alertHash, uuid: alert.uuid, pub_millis: alert.pubMillis, pub_utc_date: moment.utc(alert.pubMillis).toDate(), road_type: alert.roadType, location: JSON.stringify(alert.location), street: alert.street, city: alert.city, country: alert.country, magvar: alert.magvar, reliability: alert.reliability, report_description: alert.reportDescription, report_rating: alert.reportRating, confidence: alert.confidence, type: alert.type, subtype: alert.subtype, report_by_municipality_user: alert.reportByMunicipalityUser, thumbs_up: alert.nThumbsUp, jam_uuid: alert.jamUuid, datafile_id: data_file_id } //upsert the alert await db.upsertAlertCommand(alertEntity); //add the individual coordinate record from the location field //alerts only have 1 of these, in the location object if(alert.location){ let coord: entities.Coordinate = { id: generateCoordinateUniqueIdentifierHash(alert.location, entities.CoordinateType.Location, alertHash, null, null), alert_id: alertHash, coordinate_type_id: entities.CoordinateType.Location, latitude: alert.location.y, longitude: alert.location.x, order: 1 } await db.upsertCoordinateCommand(coord); } }); //run the tasks in a throttled fashion await throttle.all(taskList, throttleOpts); } catch (err) { console.error(err); callback(err); return err; } }; const processDataJams: Handler = async (event: wazeTypes.dataFileWithInternalId, context: Context, callback: Callback) => { try{ //patch the console so we can get more searchable logging //would be nice to make this global, but couldn't quickly get that working consolePatch(); //the event we get will actually already be JSON parsed into an object, no need to parse manually //get the startTimeMillis from the root of the file so we can use it later in our hashing let rootStart = event.startTimeMillis; //also grab the data_file_id let data_file_id = event.data_file_id; //create a list of tasks to process jams _asynchronously_ let taskList = event.jams.map((jam:wazeTypes.jam) => async () => { //hash the whole jam along with the rootStart to get a unique id let jamHash = generateAJIUniqueIdentifierHash(jam, rootStart); //build a jam object let jamEntity: entities.Jam = { id: jamHash, uuid: jam.uuid, pub_millis: jam.pubMillis, pub_utc_date: moment.utc(jam.pubMillis).toDate(), start_node: jam.startNode, end_node: jam.endNode, road_type: jam.roadType, street: jam.street, city: jam.city, country: jam.country, delay: jam.delay, speed: jam.speed, speed_kmh: jam.speedKMH, length: jam.length, turn_type: jam.turnType, level: jam.level, blocking_alert_id: jam.blockingAlertUuid, line: JSON.stringify(jam.line), type: jam.type, datafile_id: data_file_id, turn_line: JSON.stringify(jam.turnLine) } //upsert the jam await db.upsertJamCommand(jamEntity); //add the individual coordinate records from the line and turnLine fields //we won't do these in parallel because we're already running jams async //and don't want to just blast the database if (jam.line) { for (let index = 0; index < jam.line.length; index++) { const lineCoord = jam.line[index]; let coord: entities.Coordinate = { id: generateCoordinateUniqueIdentifierHash(lineCoord, entities.CoordinateType.Line, null, jamHash, null), jam_id: jamHash, coordinate_type_id: entities.CoordinateType.Line, latitude: lineCoord.y, longitude: lineCoord.x, order: index + 1 //index is zero-based, but our order is 1-based, so add 1 } await db.upsertCoordinateCommand(coord); } } if(jam.turnLine){ for (let index = 0; index < jam.turnLine.length; index++) { const turnLineCoord = jam.turnLine[index]; let coord: entities.Coordinate = { id: generateCoordinateUniqueIdentifierHash(turnLineCoord, entities.CoordinateType.TurnLine, null, jamHash, null), jam_id: jamHash, coordinate_type_id: entities.CoordinateType.TurnLine, latitude: turnLineCoord.y, longitude: turnLineCoord.x, order: index + 1 //index is zero-based, but our order is 1-based, so add 1 } await db.upsertCoordinateCommand(coord); } } }); //run the tasks in a throttled fashion await throttle.all(taskList, throttleOpts); } catch (err) { console.error(err); callback(err); return err; } }; const processDataIrregularities: Handler = async (event: wazeTypes.dataFileWithInternalId, context: Context, callback: Callback) => { try{ //patch the console so we can get more searchable logging //would be nice to make this global, but couldn't quickly get that working consolePatch(); //the event we get will actually already be JSON parsed into an object, no need to parse manually //get the startTimeMillis from the root of the file so we can use it later in our hashing let rootStart = event.startTimeMillis; //also grab the data_file_id let data_file_id = event.data_file_id; //create a list of tasks to process irregularities _asynchronously_ let taskList = event.irregularities.map((irregularity:wazeTypes.irregularity) => async () => { //hash the whole irreg along with the rootStart to get a unique id let irregularityHash = generateAJIUniqueIdentifierHash(irregularity, rootStart); //build an irreg object let irregularityEntity: entities.Irregularity = { id: irregularityHash, uuid: irregularity.id, detection_date: irregularity.detectionDate, detection_date_millis: irregularity.detectionDateMillis, detection_utc_date: moment.utc(irregularity.detectionDateMillis).toDate(), alerts_count: irregularity.alertsCount, city: irregularity.city, street: irregularity.street, country: irregularity.country, delay_seconds: irregularity.delaySeconds, seconds: irregularity.seconds, drivers_count: irregularity.driversCount, jam_level: irregularity.jamLevel, length: irregularity.length, line: JSON.stringify(irregularity.line), regular_speed: irregularity.regularSpeed, severity: irregularity.severity, speed: irregularity.speed, trend: irregularity.trend, type: irregularity.type, update_date: irregularity.updateDate, update_date_millis: irregularity.updateDateMillis, update_utc_date: moment.utc(irregularity.updateDateMillis).toDate(), is_highway: irregularity.highway, n_comments: irregularity.nComments, n_images: irregularity.nImages, n_thumbs_up: irregularity.nThumbsUp, datafile_id: data_file_id, cause_type: irregularity.causeType, end_node: irregularity.endNode, start_node: irregularity.startNode } //upsert the irreg await db.upsertIrregularityCommand(irregularityEntity); //add the individual coordinate records from the line field //we won't do these in parallel because we're already running irregs async //and don't want to just blast the database if (irregularity.line) { for (let index = 0; index < irregularity.line.length; index++) { const lineCoord = irregularity.line[index]; let coord: entities.Coordinate = { id: generateCoordinateUniqueIdentifierHash(lineCoord, entities.CoordinateType.Line, null, null, irregularityHash), irregularity_id: irregularityHash, coordinate_type_id: entities.CoordinateType.Line, latitude: lineCoord.y, longitude: lineCoord.x, order: index + 1 //index is zero-based, but our order is 1-based, so add 1 } await db.upsertCoordinateCommand(coord); } } }); //run the tasks in a throttled fashion await throttle.all(taskList, throttleOpts); } catch (err) { console.error(err); callback(err); return err; } }; // publish a simple sns message async function publishSnsMessage(message: string, topicARN: string) { let snsParams: AWS.SNS.PublishInput = { Message: JSON.stringify({source: 'waze-data-processor', message: message}), TopicArn: topicARN }; await sns.publish(snsParams).promise(); } // Read the S3 key from the retrieved SQS message function getS3KeyFromMessage(message:AWS.SQS.Message): string { // the info we need is down in the Body, because it came in via SNS // parse the body into JSON and grab the Message param let snsMessage = JSON.parse(message.Body).Message; // parse the sns message into json and get the first record let rec = JSON.parse(snsMessage).Records[0] // now from that we can get down to the s3 key return rec.s3.object.key; } // Compute the hash of the given object using our standard options function computeHash(object:Object): string { return hash(object, hashOpts); } // Generate a unique id based on the timestamp from the data root and the specific object (the whole alert, jam, irregularity, etc) function generateAJIUniqueIdentifierHash(object:Object, rootStartTime:number): string { //hash the object first let objHash = computeHash(object); //combine that hash with the timestamp let combinedObject = { rootTime: rootStartTime, originalObjectHash: objHash }; //hash the combined data and return it return computeHash(combinedObject); } // Generate a unique id based on the coordinate, type, and parent id function generateCoordinateUniqueIdentifierHash(coordinate: wazeTypes.coordinate, type: entities.CoordinateType, alertId: string, jamId: string, irregularityId: string){ //hash the coordinate first let coordHash = computeHash(coordinate); //combine the coord hash with the other data into a single object let combinedObject = { originalObjectHash: coordHash, coordinateType: type, alertId: alertId, jamId: jamId, irregularityId: irregularityId } //hash the combined data and return it return computeHash(combinedObject); } // trigger an invocation of one of the list processor lambdas function invokeListProcessor(data:wazeTypes.dataFileWithInternalId, lambdaARN:string){ return lambda.invoke({ FunctionName: lambdaARN, InvocationType: 'RequestResponse', Payload: JSON.stringify(data) }).promise(); } export {processDataFile, processDataAlerts, processDataJams, processDataIrregularities}
the_stack
import EventEmitter from 'eventemitter3'; // IMPORTANT: If you change anything in this file, make sure to also update: react-native-audio-toolkit/docs/API.md declare enum MediaStates { DESTROYED = -2, ERROR = -1, IDLE = 0, PREPARING = 1, PREPARED = 2, SEEKING = 3, PLAYING = 4, RECORDING = 4, PAUSED = 5 } declare enum PlaybackCategories { Playback = 1, Ambient = 2, SoloAmbient = 3, } interface BaseError<T> { err: "invalidpath" | "preparefail" | "startfail" | "notfound" | "stopfail" | T; message: string; stackTrace: string[] | string; } /** * For more details, see: * https://github.com/react-native-community/react-native-audio-toolkit/blob/master/docs/API.md#user-content-callbacks */ export type PlayerError = BaseError<"seekfail">; /** * For more details, see: * https://github.com/react-native-community/react-native-audio-toolkit/blob/master/docs/API.md#user-content-callbacks */ export type RecorderError = BaseError<"notsupported">; interface PlayerOptions { /** * Boolean to indicate whether the player should self-destruct after playback is finished. * If this is not set, you are responsible for destroying the object by calling `destroy()`. * (Default: true) */ autoDestroy?: boolean; /** * (Android only) Should playback continue if app is sent to background? * iOS will always pause in this case. * (Default: false) */ continuesToPlayInBackground?: boolean; /** * (iOS only) Define the audio session category * (Default: Playback) */ category?: PlaybackCategories; /** * Boolean to determine whether other audio sources on the device will mix * with sounds being played back by this module. * (Default: false) */ mixWithOthers?: boolean; } /** * Represents a media player */ declare class Player extends EventEmitter { /** * Initialize the player for playback of song in path. * * @param path Path can be either filename, network URL or a file URL to resource. * @param options */ constructor(path: string, options?: PlayerOptions); /** * Prepare playback of the file provided during initialization. This method is optional to call but might be * useful to preload the file so that the file starts playing immediately when calling `play()`. * Otherwise the file is prepared when calling `play()` which may result in a small delay. * * @param callback Callback is called with empty first parameter when file is ready for playback with `play()`. */ prepare(callback?: ((err: PlayerError | null) => void)): this; /** * Start playback. * * @param callback If callback is given, it is called when playback has started. */ play(callback?: ((err: PlayerError | null) => void)): this; /** * Pauses playback. Playback can be resumed by calling `play()` with no parameters. * * @param callback Callback is called after the operation has finished. */ pause(callback?: ((err: PlayerError | null) => void)): this; /** * Helper method for toggling pause. * * @param callback Callback is called after the operation has finished. Callback receives Object error as first * argument, Boolean paused as second argument indicating if the player ended up playing (`false`) * or paused (`true`). */ playPause(callback?: ((err: PlayerError | null, paused: boolean) => void)): this; /** * Stop playback. If autoDestroy option was set during initialization, clears all media resources from memory. * In this case the player should no longer be used. * * @param callback */ stop(callback?: ((err: PlayerError | null) => void)): this; /** * Stops playback and destroys the player. The player should no longer be used. * * @param callback Callback is called after the operation has finished. */ destroy(callback?: ((err: PlayerError | null) => void)): void; /** * Seek in currently playing media. * * @param position Position is the offset from the start. * @param callback If callback is given, it is called when the seek operation completes. If another seek * operation is performed before the previous has finished, the previous operation gets an error in its * callback with the err field set to oldcallback. The previous operation should likely do nothing in this case. */ seek(position?: number, callback?: ((err: PlayerError | null) => void)): void; /** * Get/set playback volume. The scale is from 0.0 (silence) to 1.0 (full volume). Default is 1.0. */ volume: number; /** * Get/set current playback position in milliseconds. It's recommended to do seeking via `seek()`, * as it is not possible to pass a callback when setting the `currentTime` property. */ currentTime: number; /** * Get/set wakeLock on player, keeping it alive in the background. Default is `false`. Android only. */ wakeLock: boolean; /** * Get/set looping status of the current file. If `true`, file will loop when playback reaches end of file. * Default is `false`. */ looping: boolean; /** * Get/set the playback speed for audio. * Default is `1.0`. * * NOTE: On Android, this is only supported on Android 6.0+. */ speed: number; /** * Get duration of prepared/playing media in milliseconds. * If no duration is available (for example live streams), `-1` is returned. */ readonly duration: number; /** * Get the playback state. */ readonly state: MediaStates; /** * `true` if player can begin playback. */ readonly canPlay: boolean; /** * `true` if player can stop playback. */ readonly canStop: boolean; /** * `true` if player can prepare for playback. */ readonly canPrepare: boolean; /** * `true` if player is playing. */ readonly isPlaying: boolean; /** * `true` if player is stopped. */ readonly isStopped: boolean; /** * `true` if player is paused. */ readonly isPaused: boolean; /** * `true` if player is prepared. */ readonly isPrepared: boolean; } interface RecorderOptions { /** * Set bitrate for the recorder, in bits per second (Default: 128000) */ bitrate: number; /** * Set number of channels (Default: 2) */ channels: number; /** * Set how many samples per second (Default: 44100) */ sampleRate: number; /** * Override format. Possible values: * - Cross-platform: 'mp4', 'aac' * - Android only: 'ogg', 'webm', 'amr' * * (Default: based on filename extension) */ format: string; /** * Override encoder. Android only. * * Possible values: 'aac', 'mp4', 'webm', 'ogg', 'amr' * * (Default: based on filename extension) */ encoder: string; /** * Quality of the recording, iOS only. * * Possible values: 'min', 'low', 'medium', 'high', 'max' * * (Default: 'medium') */ quality: string; /** * Optional argument to activate metering events. * This will cause a 'meter' event to fire every given milliseconds, * e.g. 250 will fire 4 time in a second. */ meteringInterval: number; } /** * Represents a media recorder */ declare class Recorder extends EventEmitter { /** * Initialize the recorder for recording to file in `path`. * * @param path Path can either be a filename or a file URL (Android only). * @param options */ constructor(path: string, options?: RecorderOptions); /** * Prepare recording to the file provided during initialization. This method is optional to call but it may be * beneficial to call to make sure that recording begins immediately after calling `record()`. Otherwise the * recording is prepared when calling `record()` which may result in a small delay. * * NOTE: Assume that this wipes the destination file immediately. * * @param callback When ready to record using `record()`, the callback is called with an empty first parameter. * Second parameter contains a path to the destination file on the filesystem. * * If there was an error, the callback is called with an error object as first parameter. */ prepare(callback?: ((err: RecorderError | null, fsPath: string) => void)): this; /** * Start recording to file in `path`. * * @param callback Callback is called after recording has started or with error object if an error occurred. */ record(callback?: ((err: RecorderError | null) => void)): this; /** * Stop recording and save the file. * * @param callback Callback is called after recording has stopped or with error object. * The recorder is destroyed after calling stop and should no longer be used. */ stop(callback?: ((err: RecorderError | null) => void)): this; /** * * @param callback */ pause(callback?: ((err: RecorderError | null) => void)): this; /** * * @param callback */ toggleRecord(callback?: ((err: RecorderError | null) => void)): this; /** * Destroy the recorder. Should only be used if a recorder was constructed, and for some reason is now unwanted. * * @param callback Callback is called after the operation has finished. */ destroy(callback?: ((err: RecorderError | null) => void)): void; /** * Get the filesystem path of file being recorded to. * Available after `prepare()` call has invoked its callback successfully. */ readonly fsPath: string; /** * Get the recording state. */ readonly state: MediaStates; /** * `true` if recorder can begin recording. */ readonly canRecord: boolean; /** * `true` if recorder can prepare for recording. */ readonly canPrepare: boolean; /** * `true` if recorder is recording. */ readonly isRecording: boolean; /** * `true` if recorder is prepared. */ readonly isPrepared: boolean; } export { Player, Recorder, MediaStates };
the_stack
import { ExpiryTimeType } from '@fluid-experimental/property-properties'; import Button from '@material-ui/core/Button'; import FormControl from '@material-ui/core/FormControl'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Radio from '@material-ui/core/Radio'; import RadioGroup from '@material-ui/core/RadioGroup'; import { makeStyles, Theme } from '@material-ui/core/styles'; import classNames from 'classnames'; import React, { useEffect, useState } from 'react'; import { IExpiryInfo, IExpiryState, IRepoExpiryGetter, IRepoExpirySetter } from './CommonTypes'; import { LoadingButton } from './LoadingButton'; import { CustomChip } from './CustomChip'; import { ErrorPopup } from './ErrorPopup'; import { backGroundGrayColor, textDarkColor } from './constants'; import { InspectorModal } from './InspectorModal'; const useStyles = makeStyles((theme: Theme) => ({ annotation: { color: textDarkColor + 'b3', // 8 digit hex code with alpha 0.7 fontSize: '12px', }, cancelButton: { 'margin-right': theme.spacing(1.5), }, contentContainer: { 'color': textDarkColor, 'display': 'flex', 'flex-direction': 'column', 'justify-content': 'space-between', }, deleteButton: { '&:hover': { background: '#C01010', }, 'background': '#DD2222', 'color': backGroundGrayColor, }, deleteLink: { color: '#FF2222', }, expiryStateChip: { '&.expired': { background: '#FAA21B', }, '&.live': { background: '#87B340', }, 'align-items': 'center', 'color': 'white', 'display': 'inline-flex', }, horizontalButtonContainer: { alignItems: 'center', display: 'flex', justifyContent: 'flex-end', marginTop: '10px', }, horizontalContainer: { alignItems: 'center', display: 'flex', justifyContent: 'space-between', marginBottom: theme.spacing(2), }, label: { fontWeight: 'bold', }, legend: { marginBottom: theme.spacing(2), }, radioGroup: { '&>*': { marginBottom: theme.spacing(1.5), }, }, selectionLabel: { lineHeight: '1.2', paddingLeft: theme.spacing(2), }, textButton: { '&:hover': { background: 'transparent', cursor: 'pointer', textDecorationLine: 'underline', }, 'align-self': 'flex-end', 'padding-bottom': theme.spacing(1.5), 'padding-right': '3px', }, }), { name: 'ExpiryModal' }); interface IModalExpiryState { expiresIn: string; expiryState: IExpiryState; } interface IModalState { mode: 'default' | 'expirySelection' | 'deletion'; } interface IModalPolicyState { retentionStrategy: ExpiryTimeType; updating: boolean; } interface IModalDeletionState { deleting: boolean; } export interface IExpiryModalProps { deleteRepo: (repoUrn: string) => Promise<void>; getRepoExpiry: IRepoExpiryGetter; setRepoExpiry: IRepoExpirySetter; isV1Urn: boolean; repositoryUrn?: string; onClosed: () => void; } const retentionStrategyDescriptions: { [key in ExpiryTimeType]: string } = { persistent: 'The repo does never expire', temporary: 'The repo expires after 30 days', transient: 'The repo expires after 24 hours', }; const lifeCycleDescriptions: { [key in IExpiryState]: string } = { expired: 'Expired State', live: 'Live State', }; const expiryPlaceHolder = 'loading...'; /** * An info modal. */ export const ExpiryModal: React.FunctionComponent<IExpiryModalProps> = (props) => { const classes = useStyles(); const { deleteRepo, getRepoExpiry, isV1Urn, onClosed, repositoryUrn, setRepoExpiry } = props; // ### Utilities and state management ### // NOTE: Setting multiple state variables independently will lead to multiple render passes unfortunately. // It is inevitable though, because handling all state in just one state object doesn't work if we update it several // times in nested promises (we'll end up with an inconsistent state because consecutive updates will not be merged // properly). const [modalState, setModalState] = useState<IModalState>({ mode: 'default' }); const [modalExpiryState, setModalExpiryState] = useState<IModalExpiryState>({ expiresIn: expiryPlaceHolder, expiryState: 'live', }); const [deletionState, setDeletionState] = useState<IModalDeletionState>({ deleting: false }); const [policyState, setPolicyState] = useState<IModalPolicyState>({retentionStrategy: 'temporary', updating: false}); // Get a promise that resolves with the expiry information for the current repository. const getExpiryInfo = (): Promise<IExpiryInfo | void> => { return ErrorPopup(getRepoExpiry.bind(null, repositoryUrn!)); }; /** * Transform expiry information to a state object. * @param expiryInfo The expiry information object. */ const expiryInfoToState = (expiryInfo: IExpiryInfo): IModalExpiryState => { const newState = {} as IModalExpiryState; newState.expiryState = expiryInfo.state; if (expiryInfo.when) { newState.expiresIn = new Date(expiryInfo.when).toLocaleString(); } else { newState.expiresIn = 'never'; } return newState; }; /** * Set the expiration state of this modal. * @param newState If present, it will be set as the new state of the modal. Otherwise, {{getExpiryInfo}} will be * called and its return values will be used to fill the state. */ const setExpiryState = (newState?: IModalExpiryState) => { if (newState) { setModalExpiryState(newState); } else { getExpiryInfo().then((expiryInfo) => { if (expiryInfo) { newState = expiryInfoToState(expiryInfo); setModalExpiryState(newState); } }); } }; /** * Set the expiry of the current repository to the provided retention policy * @param expiryTime The new retention policy/expiry time. */ const setExpiry = (expiryTime: ExpiryTimeType): Promise<void> => { setPolicyState({ ...policyState, updating: true }); setModalExpiryState({ ...modalExpiryState, expiresIn: expiryPlaceHolder }); return ErrorPopup(setRepoExpiry.bind(null, repositoryUrn!, expiryTime)).then(() => { setModalState({ mode: 'default' }); getExpiryInfo().then((expiryInfo) => { if (expiryInfo) { const newState = expiryInfoToState(expiryInfo); setModalExpiryState(newState); setPolicyState({ ...policyState, updating: false }); } }); }); }; const setRetentionPolicy = (event) => { setPolicyState({ ...policyState, retentionStrategy: event.target.value }); }; const deleteRepository = (repoUrn: string) => { setDeletionState({ deleting: true }); setModalExpiryState({ ...modalExpiryState, expiresIn: expiryPlaceHolder }); return ErrorPopup(deleteRepo.bind(null, repoUrn)).then(() => { setModalState({ mode: 'default' }); setDeletionState({ deleting: false }); setExpiryState(); }); }; useEffect(setExpiryState, [repositoryUrn]); // ### Rendering ### // Renders the modal title const renderTitle = () => { return ( modalState.mode === 'default' ? 'Repository Expiry' : modalState.mode === 'expirySelection' ? 'Set a new retention policy' : 'Delete Repository' ); }; // Renders the life cycle state chip or placeholder const renderLifeCycleState = () => { let lifeCycle; if (modalExpiryState.expiresIn === expiryPlaceHolder) { lifeCycle = ( <span> {modalExpiryState.expiresIn} </span> ); } else { lifeCycle = ( <CustomChip height={30} label={lifeCycleDescriptions[modalExpiryState.expiryState]} className={classNames(classes.expiryStateChip, [modalExpiryState.expiryState])} /> ); } return lifeCycle; }; // Renders the main view of the modal const renderExpiryOverview = () => { return ( <div className={classes.contentContainer}> <span className={classes.annotation}>Current Lifecycle State</span> <div className={classes!.horizontalContainer}> {renderLifeCycleState()} <Button id='delete-repository' color='primary' className={classes.textButton} classes={{ textPrimary: classes.deleteLink }} disabled={modalExpiryState.expiresIn === expiryPlaceHolder || modalExpiryState.expiryState === 'expired'} onClick={() => { setModalState({ mode: 'deletion' }); }} > Delete Repository </Button> </div> <span className={classes.annotation}> {modalExpiryState.expiryState === 'live' ? 'Expiry' : 'Deletion'} date </span> <div className={classes!.horizontalContainer}> <span> {modalExpiryState.expiresIn} </span> <Button id='set-expiry' color='primary' className={classes.textButton} disabled={modalExpiryState.expiresIn === expiryPlaceHolder} onClick={() => { setModalState({ mode: 'expirySelection' }); }} > Set a new expiry </Button> </div> <div className={classes.horizontalButtonContainer}> <Button color='primary' variant='contained' onClick={onClosed} > Ok </Button> </div> </div> ); }; const renderSelectionLabel = (policy: ExpiryTimeType) => { let policyName: string = policy.toString(); policyName = policyName.substr(0, 1).toUpperCase() + policyName.substring(1); return ( <div className={classes.selectionLabel}> <span className={classes.label}> {policyName}<br /> </span> <span className={classes.annotation}> {retentionStrategyDescriptions[policy]} </span> </div> ); }; // Renders the expiration selection view (when clicking on 'set a new expiry'). const renderNewExpirySelection = () => { const radioButton = () => { return ( <Radio color='primary' /> ); }; return ( <div className={classes.contentContainer}> <FormControl component={'fieldset' as 'div'}> <span className={classes.legend}>Select one of following expiry options:</span> <RadioGroup aria-label='policy' className={classes.radioGroup} name='policy' onChange={setRetentionPolicy} value={policyState.retentionStrategy} > <FormControlLabel value='transient' control={radioButton()} label={renderSelectionLabel('transient')} /> <FormControlLabel value='temporary' control={radioButton()} label={renderSelectionLabel('temporary')} /> <FormControlLabel value='persistent' control={radioButton()} label={renderSelectionLabel('persistent')} /> </RadioGroup> </FormControl> <div className={classes.horizontalButtonContainer}> <Button color='primary' disabled={policyState.updating} variant='outlined' className={classes.cancelButton} onClick={() => { setModalState({ mode: 'default' }); }} > Cancel </Button> <LoadingButton color='primary' onClick={() => setExpiry(policyState.retentionStrategy)} variant='contained' > Update </LoadingButton> </div> </div> ); }; // Renders the confirmation dialog for deleting a repository const renderDeletionConfirmation = () => { return ( <div className={classes.contentContainer}> Are you sure you want to delete this repository?<br /> By deleting it, the Lifecycle State will change to 'Expired' for 30 days before being destroyed. { isV1Urn && <span><br /> Note: You are using a v1 branch urn. You will need to convert it into a v2 urn in order to undelete this repository in the inspector app.<br /><br /> </span> } <div className={classes.horizontalButtonContainer}> <Button color='primary' disabled={deletionState.deleting} variant='outlined' className={classes.cancelButton} onClick={() => { setModalState({ mode: 'default' }); }} > Cancel </Button> <LoadingButton classes={{ contained: classes.deleteButton }} onClick={() => deleteRepository(repositoryUrn!)} variant='contained' > Yes, delete </LoadingButton> </div> </div> ); }; return ( <InspectorModal title={`${renderTitle()}`}> {modalState.mode === 'default' ? renderExpiryOverview() : modalState.mode === 'expirySelection' ? renderNewExpirySelection() : renderDeletionConfirmation() } </InspectorModal> ); };
the_stack
import * as im from 'immutable'; import * as lexical from './lexical'; export type CodePoints = im.List<string>; export const makeCodePoints = (str: string): CodePoints => { // NOTE: Splitting a string by Unicode code points is tricky in // JavaScript. We use the spread operator here, because it does // the split correctly (versus, say, `String.split). return im.List([...str]); } // TODO: Refactor this into a member of `CodePoints`. export const stringSlice = ( points: CodePoints, begin?: number, end?: number ): string => { return points.slice(begin, end).join(""); } // --------------------------------------------------------------------------- // Fodder // // Fodder is stuff that is usually thrown away by lexers/preprocessors // but is kept so that the source can be round tripped with full // fidelity. export type FodderKind = "FodderWhitespace" | "FodderCommentC" | "FodderCommentCpp" | "FodderCommentHash"; export interface FodderElement { readonly kind: FodderKind data: string } export type Fodder = FodderElement[]; // --------------------------------------------------------------------------- // Token export type TokenKind = // Symbols "TokenBraceL" | "TokenBraceR" | "TokenBracketL" | "TokenBracketR" | "TokenComma" | "TokenDollar" | "TokenDot" | "TokenParenL" | "TokenParenR" | "TokenSemicolon" | // Arbitrary length lexemes "TokenIdentifier" | "TokenNumber" | "TokenOperator" | "TokenStringBlock" | "TokenStringDouble" | "TokenStringSingle" | "TokenCommentCpp" | "TokenCommentC" | "TokenCommentHash" | // Keywords "TokenAssert" | "TokenElse" | "TokenError" | "TokenFalse" | "TokenFor" | "TokenFunction" | "TokenIf" | "TokenImport" | "TokenImportStr" | "TokenIn" | "TokenLocal" | "TokenNullLit" | "TokenSelf" | "TokenSuper" | "TokenTailStrict" | "TokenThen" | "TokenTrue" | // A special token that holds line/column information about the end // of the file. "TokenEndOfFile"; export const TokenKindStrings = im.Map<TokenKind, string>({ // Symbols TokenBraceL: "\"{\"", TokenBraceR: "\"}\"", TokenBracketL: "\"[\"", TokenBracketR: "\"]\"", TokenComma: "\",\"", TokenDollar: "\"$\"", TokenDot: "\".\"", TokenParenL: "\"(\"", TokenParenR: "\")\"", TokenSemicolon: "\";\"", // Arbitrary length lexemes TokenIdentifier: "IDENTIFIER", TokenNumber: "NUMBER", TokenOperator: "OPERATOR", TokenStringBlock: "STRING_BLOCK", TokenStringDouble: "STRING_DOUBLE", TokenStringSingle: "STRING_SINGLE", TokenCommentCpp: "CPP_COMMENT", TokenCommentC: "C_COMMENT", TokenCommentHash: "HASH_COMMENT", // Keywords TokenAssert: "assert", TokenElse: "else", TokenError: "error", TokenFalse: "false", TokenFor: "for", TokenFunction: "function", TokenIf: "if", TokenImport: "import", TokenImportStr: "importstr", TokenIn: "in", TokenLocal: "local", TokenNullLit: "null", TokenSelf: "self", TokenSuper: "super", TokenTailStrict: "tailstrict", TokenThen: "then", TokenTrue: "true", // A special token that holds line/column information about the end // of the file. TokenEndOfFile: "end of file", }); export class Token { constructor( readonly kind: TokenKind, // The type of the token readonly fodder: Fodder | null, // Any fodder the occurs before this token readonly data: string, // Content of the token if it is not a keyword // Extra info for when kind == tokenStringBlock readonly stringBlockIndent: string, // The sequence of whitespace that indented the block. readonly stringBlockTermIndent: string, // This is always fewer whitespace characters than in stringBlockIndent. readonly loc: lexical.LocationRange, ) {} public toString(): string { const tokenKind = TokenKindStrings.get(this.kind); if (this.data == "") { return tokenKind; } else if (this.kind == "TokenOperator") { return `"${this.data}"`; } else { return `(${tokenKind}, "${this.data}")`; } } } export type Tokens = im.List<Token>; export const emptyTokens = im.List<Token>(); // --------------------------------------------------------------------------- // Helpers export const isUpper = (r: rune): boolean => { return r.data >= 'A' && r.data <= 'Z' } export const isLower = (r: rune): boolean => { return r.data >= 'a' && r.data <= 'z' } export const isNumber = (r: rune): boolean => { return r.data >= '0' && r.data <= '9' } export const isIdentifierFirst = (r: rune): boolean => { return isUpper(r) || isLower(r) || r.data === '_' } export const isIdentifier = (r: rune): boolean => { return isIdentifierFirst(r) || isNumber(r) } export const isSymbol = (r: rune): boolean => { switch (r.data) { case '!': case '$': case ':': case '~': case '+': case '-': case '&': case '|': case '^': case '=': case '<': case '>': case '*': case '/': case '%': return true } return false } // Check that b has at least the same whitespace prefix as a and // returns the amount of this whitespace, otherwise returns 0. If a // has no whitespace prefix than return 0. export const checkWhitespace = (a: string, b: string): number => { let i = 0; for ( ; i < a.length; i++) { if (a[i] != ' ' && a[i] != '\t') { // a has run out of whitespace and b matched up to this point. // Return result. return i } if (i >= b.length) { // We ran off the edge of b while a still has whitespace. // Return 0 as failure. return 0 } if (a[i] != b[i]) { // a has whitespace but b does not. Return 0 as failure. return 0 } } // We ran off the end of a and b kept up return i } // --------------------------------------------------------------------------- // Lexer export interface rune { readonly codePoint: number, readonly data: string, }; // NOTE: `pos` is the index of the code point, not the index of a byte // in the string. export const runeFromString = (str: string, pos: number) => { return runeFromCodePoints(makeCodePoints(str), pos); }; export const runeFromCodePoints = (str: CodePoints, pos: number) => { const r = str.get(pos), codePoint = r.codePointAt(0); return <rune>{ codePoint: codePoint, data: r, } }; const LexEOF = <rune> { codePoint: -1, data: "\0", }; // TODO: Replace this. This is because we need a special rune type in // TS, but it should be phased out. const LexEOFPos = -1; export class lexer { fileName: string // The file name being lexed, only used for errors input: CodePoints // The input string pos: number // Current byte position in input lineNumber: number // Current line number for pos lineStart: number // Byte position of start of line // Data about the state position of the lexer before previous call // to 'next'. If this state is lost then prevPos is set to lexEOF // and panic ensues. prevPos: number // Byte position of last rune read prevLineNumber: number // The line number before last rune read prevLineStart: number // The line start before last rune read tokens: im.List<Token> // The tokens that we've generated so far // Information about the token we are working on right now fodder: FodderElement[] tokenStart: number tokenStartLoc: lexical.Location constructor(fn: string, input: string) { this.fileName = fn; this.input = makeCodePoints(input); this.lineNumber = 1; this.prevPos = LexEOFPos; this.prevLineNumber = 1; this.tokenStartLoc = new lexical.Location(1, 1); this.tokens = im.List<Token>(); this.fodder = []; this.pos = 0; this.lineStart = 0; this.tokenStart = 0; this.prevLineStart = 0; }; // next returns the next rune in the input. public next = (): rune => { if (this.pos >= this.input.count()) { this.prevPos = this.pos; return LexEOF; } const r = runeFromCodePoints(this.input, this.pos); // NOTE: Because `CodePoints` is essentially an array of distinct // code points, rather than an array of bytes. So unlike the Go // implementation of this code, `pos` only ever needs to be // advanced by 1 (rather than the number of bytes a code point // takes up). this.prevPos = this.pos; this.pos += 1 if (r.data === '\n') { this.prevLineNumber = this.lineNumber; this.prevLineStart = this.lineStart; this.lineNumber++; this.lineStart = this.pos; } return r; }; public acceptN = (n: number) => { for (let i = 0; i < n; i++) { this.next() } }; // peek returns but does not consume the next rune in the input. public peek = (): rune => { if (this.pos >= this.input.count()) { this.prevPos = this.pos; return LexEOF; } const r = runeFromCodePoints(this.input, this.pos); return r; }; // backup steps back one rune. Can only be called once per call of // next. public backup = () => { if (this.prevPos === LexEOFPos) { throw new Error( "INTERNAL ERROR: backup called with no valid previous rune"); } if ((this.prevPos - this.lineStart) < 0) { this.lineNumber = this.prevLineNumber; this.lineStart = this.prevLineStart; } this.pos = this.prevPos; this.prevPos = LexEOFPos; }; public location = (): lexical.Location => { return new lexical.Location(this.lineNumber, this.pos - this.lineStart + 1); }; public prevLocation = (): lexical.Location => { if (this.prevPos == LexEOFPos) { throw new Error( "INTERNAL ERROR: prevLocation called with no valid previous rune"); } return new lexical.Location( this.prevLineNumber, this.prevPos - this.prevLineStart + 1); }; // Reset the current working token start to the current cursor // position. This may throw away some characters. This does not // throw away any accumulated fodder. public resetTokenStart = () => { this.tokenStart = this.pos this.tokenStartLoc = this.location() }; public emitFullToken = ( kind: TokenKind, data: string, stringBlockIndent: string, stringBlockTermIndent: string ) => { this.tokens = this.tokens.push(new Token( kind, this.fodder, data, stringBlockIndent, stringBlockTermIndent, lexical.MakeLocationRange( this.fileName, this.tokenStartLoc, this.location()), )); this.fodder = []; }; public emitToken = (kind: TokenKind) => { this.emitFullToken( kind, stringSlice(this.input, this.tokenStart, this.pos), "", ""); this.resetTokenStart(); }; public addWhitespaceFodder = () => { const fodderData = stringSlice(this.input, this.tokenStart, this.pos); if (this.fodder.length == 0 || this.fodder[this.fodder.length-1].kind != "FodderWhitespace") { this.fodder.push(<FodderElement>{ kind: "FodderWhitespace", data: fodderData }); } else { this.fodder[this.fodder.length-1].data += fodderData; } this.resetTokenStart(); }; public addCommentFodder = (kind: FodderKind) => { const fodderData = stringSlice(this.input, this.tokenStart,this.pos); this.fodder.push(<FodderElement>{kind: kind, data: fodderData}); this.resetTokenStart() }; public addFodder = (kind: FodderKind, data: string) => { this.fodder.push(<FodderElement>{kind: kind, data: data}); }; // lexNumber will consume a number and emit a token. It is assumed // that the next rune to be served by the lexer will be a leading // digit. public lexNumber = (): lexical.StaticError | null => { // This function should be understood with reference to the linked // image: http://www.json.org/number.gif // Note, we deviate from the json.org documentation as follows: // There is no reason to lex negative numbers as atomic tokens, it // is better to parse them as a unary operator combined with a // numeric literal. This avoids x-1 being tokenized as // <identifier> <number> instead of the intended <identifier> // <binop> <number>. type numLexState = "numBegin" | "numAfterZero" | "numAfterOneToNine" | "numAfterDot" | "numAfterDigit" | "numAfterE" | "numAfterExpSign" | "numAfterExpDigit"; let state = "numBegin" outerLoop: while (true) { const r = this.next(); switch (state) { case "numBegin": { if (r.data === '0') { state = "numAfterZero"; } else if (r.data >= '1' && r.data <= '9') { state = "numAfterOneToNine"; } else { // The caller should ensure the first rune is a digit. throw new Error("INTERNAL ERROR: Couldn't lex number"); } break; } case "numAfterZero": { if (r.data === '.') { state = "numAfterDot"; } else if (r.data === 'e' || r.data === 'E') { state = "numAfterE"; } else { break outerLoop; } break; } case "numAfterOneToNine": { if (r.data === '.') { state = "numAfterDot"; } else if (r.data === 'e' || r.data === 'E') { state = "numAfterE"; } else if (r.data >= '0' && r.data <= '9') { state = "numAfterOneToNine"; } else { break outerLoop; } break; } case "numAfterDot": { if (r.data >= '0' && r.data <= '9') { state = "numAfterDigit"; } else { return lexical.MakeStaticErrorPoint( `Couldn't lex number, junk after decimal point: '${r.data}'`, this.fileName, this.prevLocation()); } break; } case "numAfterDigit": { if (r.data === 'e' || r.data === 'E') { state = "numAfterE"; } else if (r.data >= '0' && r.data <= '9') { state = "numAfterDigit"; } else { break outerLoop; } break; } case "numAfterE": { if (r.data === '+' || r.data === '-') { state = "numAfterExpSign"; } else if(r.data >= '0' && r.data <= '9') { state = "numAfterExpDigit"; } else { return lexical.MakeStaticErrorPoint( `Couldn't lex number, junk after 'E': '${r.data}'`, this.fileName, this.prevLocation()); } break; } case "numAfterExpSign": { if (r.data >= '0' && r.data <= '9') { state = "numAfterExpDigit"; } else { return lexical.MakeStaticErrorPoint( `Couldn't lex number, junk after exponent sign: '${r.data}'`, this.fileName, this.prevLocation()); } break; } case "numAfterExpDigit": { if (r.data >= '0' && r.data <= '9') { state = "numAfterExpDigit"; } else { break outerLoop; } break; } } } this.backup(); this.emitToken("TokenNumber"); return null; }; // lexIdentifier will consume a identifer and emit a token. It is // assumed that the next rune to be served by the lexer will be a // leading digit. This may emit a keyword or an identifier. public lexIdentifier = () => { let r = this.next(); if (!isIdentifierFirst(r)) { throw new Error("INTERNAL ERROR: Unexpected character in lexIdentifier"); } for (; r.codePoint != LexEOF.codePoint; r = this.next()) { if (!isIdentifier(r)) { break; } } this.backup(); switch (stringSlice(this.input, this.tokenStart, this.pos)) { case "assert": this.emitToken("TokenAssert"); break; case "else": this.emitToken("TokenElse"); break; case "error": this.emitToken("TokenError"); break; case "false": this.emitToken("TokenFalse"); break; case "for": this.emitToken("TokenFor"); break; case "function": this.emitToken("TokenFunction"); break; case "if": this.emitToken("TokenIf"); break; case "import": this.emitToken("TokenImport"); break; case "importstr": this.emitToken("TokenImportStr"); break; case "in": this.emitToken("TokenIn"); break; case "local": this.emitToken("TokenLocal"); break; case "null": this.emitToken("TokenNullLit"); break; case "self": this.emitToken("TokenSelf"); break; case "super": this.emitToken("TokenSuper"); break; case "tailstrict": this.emitToken("TokenTailStrict"); break; case "then": this.emitToken("TokenThen"); break; case "true": this.emitToken("TokenTrue"); break; default: // Not a keyword, assume it is an identifier this.emitToken("TokenIdentifier") break; }; }; // lexSymbol will lex a token that starts with a symbol. This could // be a C or C++ comment, block quote or an operator. This function // assumes that the next rune to be served by the lexer will be the // first rune of the new token. public lexSymbol(): lexical.StaticError | null { let r = this.next(); // Single line C++ style comment if (r.data === '/' && this.peek().data === '/') { this.next(); this.resetTokenStart(); // Throw out the leading // for (r = this.next(); r.codePoint != LexEOF.codePoint && r.data !== '\n'; r = this.next()) { } // Leave the '\n' in the lexer to be fodder for the next round this.backup(); this.emitToken("TokenCommentCpp"); return null; } if (r.data === '/' && this.peek().data === '*') { const commentStartLoc = this.tokenStartLoc; this.next(); // consume the '*' this.resetTokenStart(); // Throw out the leading /* for (r = this.next(); ; r = this.next()) { if (r.codePoint == LexEOF.codePoint) { return lexical.MakeStaticErrorPoint("Multi-line comment has no terminating */", this.fileName, commentStartLoc) } if (r.data === '*' && this.peek().data === '/') { // Don't include trailing */ this.backup(); this.emitToken("TokenCommentC"); this.next(); // Skip past '*' this.next(); // Skip past '/' this.resetTokenStart(); // Start next token at this point return null; } } } if (r.data === '|' && stringSlice(this.input, this.pos).startsWith("||\n")) { const commentStartLoc = this.tokenStartLoc this.acceptN(3) // Skip "||\n" var cb = im.List<rune>(); // Skip leading blank lines for (r = this.next(); r.data === '\n'; r = this.next()) { cb = cb.push(r); } this.backup(); let numWhiteSpace = checkWhitespace( stringSlice(this.input, this.pos), stringSlice(this.input, this.pos)); const stringBlockIndent = stringSlice(this.input, this.pos, this.pos+numWhiteSpace); if (numWhiteSpace == 0) { return lexical.MakeStaticErrorPoint( "Text block's first line must start with whitespace", this.fileName, commentStartLoc); } while (true) { if (numWhiteSpace <= 0) { throw new Error("INTERNAL ERROR: Unexpected value for numWhiteSpace"); } this.acceptN(numWhiteSpace); for (r = this.next(); r.data !== '\n'; r = this.next()) { if (r.codePoint == LexEOF.codePoint) { return lexical.MakeStaticErrorPoint("Unexpected EOF", this.fileName, commentStartLoc); } cb = cb.push(r); } cb = cb.push(runeFromString("\n", 0)); // Skip any blank lines for (r = this.next(); r.data === '\n'; r = this.next()) { cb = cb.push(r); } this.backup() // Look at the next line numWhiteSpace = checkWhitespace( stringBlockIndent, stringSlice(this.input, this.pos)); if (numWhiteSpace == 0) { // End of the text block let stringBlockTermIndent: string = ""; for (r = this.next(); r.data === ' ' || r.data === '\t'; r = this.next()) { stringBlockTermIndent = stringBlockIndent.concat(r.data); } this.backup(); if (!stringSlice(this.input, this.pos).startsWith("|||")) { return lexical.MakeStaticErrorPoint( "Text block not terminated with |||", this.fileName, commentStartLoc) } this.acceptN(3) // Skip '|||' const tokenData = cb .map((rune: rune) => { return rune.data; }) .join(""); this.emitFullToken("TokenStringBlock", tokenData, stringBlockIndent, stringBlockTermIndent); this.resetTokenStart(); return null; } } } // Assume any string of symbols is a single operator. for (r = this.next(); isSymbol(r); r = this.next()) { // Not allowed // in operators if (r.data === '/' && stringSlice(this.input, this.pos).startsWith("/")) { break; } // Not allowed /* in operators if (r.data === '/' && stringSlice(this.input, this.pos).startsWith("*")) { break; } // Not allowed ||| in operators if (r.data === '|' && stringSlice(this.input, this.pos).startsWith("||")) { break; } } this.backup(); // Operators are not allowed to end with + - ~ ! unless they are // one rune long. So, wind it back if we need to, but stop at the // first rune. This relies on the hack that all operator symbols // are ASCII and thus there is no need to treat this substring as // general UTF-8. for (r = runeFromCodePoints(this.input, this.pos-1); this.pos > this.tokenStart+1; this.pos--) { switch (r.data) { case '+': case '-': case '~': case '!': continue; } break; } if (stringSlice(this.input, this.tokenStart, this.pos) == "$") { this.emitToken("TokenDollar") } else { this.emitToken("TokenOperator") } return null; }; // locBeforeLastTokenRange checks whether a location specified by // `loc` exists before the range of coordinates of the last token // terminates. public locBeforeLastTokenRange = (loc: lexical.Location): boolean => { const numTokens = this.tokens.count(); if (loc.line == -1 && loc.column == -1) { return false; } else if (numTokens == 0) { return false; } const lastLocRange = this.tokens.get(numTokens-1).loc; return loc.line < lastLocRange.begin.line || (loc.line == lastLocRange.begin.line && loc.column < lastLocRange.begin.column) }; // locInLastTokenRange checks whether a location specified by `loc` // exists within the range of coordinates of the last token. public locInLastTokenRange = (loc: lexical.Location): boolean => { const numTokens = this.tokens.count(); if (loc.line == -1 && loc.column == -1) { return false; } else if (numTokens == 0) { return false; } const lastToken = this.tokens.get(numTokens-1); const lastLocRange = lastToken.loc; if ((lastLocRange.begin.line == loc.line) && loc.line == lastLocRange.end.line && lastLocRange.begin.column <= loc.column && loc.column <= lastLocRange.end.column) { return true; } else if ((lastLocRange.begin.line < loc.line) && loc.line == lastLocRange.end.line && loc.column <= lastLocRange.end.column) { return true; } else if ((lastLocRange.begin.line == loc.line) && loc.line < lastLocRange.end.line && loc.column >= lastLocRange.begin.column) { return true; } else if ((lastLocRange.begin.line < loc.line) && loc.line < lastLocRange.end.line) { return true; } else { return false; } }; // checkTruncateTokenRange truncates the token stream if it exceeds // the token range. Note that a corner case is if the range max // happens to occur in whitespace; in this case, we will truncate at // the last token that occurs before the whitespace begins. public checkTruncateTokenRange = (rangeMax: lexical.Location): boolean => { if (rangeMax.line == -1 && rangeMax.column == -1) { return false; } const numTokens = this.tokens.count(); // Lex at least one token before returning. if (numTokens == 0) { return false } while (true) { // If we have truncated all the tokens in the stream, return. if (numTokens == 0) { return true } // Return if location is in the range of the last token. if (this.locInLastTokenRange(rangeMax)) { return true } // If token range max occurs before the last token range starts, // truncate and return. if (this.locBeforeLastTokenRange(rangeMax)) { this.tokens = this.tokens.pop(); // Stop truncating after the condition is no longer true. if (!this.locBeforeLastTokenRange(rangeMax)) { return true; } continue; } return false; } }; } export const Lex = ( fn: string, input: string ): Tokens | lexical.StaticError => { const unlimitedRange = new lexical.Location(-1, -1); return LexRange(fn, input, unlimitedRange); } export const LexRange = ( fn: string, input: string, tokenRange: lexical.Location, ): Tokens | lexical.StaticError => { const l = new lexer(fn, input); let err: lexical.StaticError | null = null; for (let r = l.next(); r.codePoint != LexEOF.codePoint; r = l.next()) { // Terminate lexing if we're past the token range. If we've lexed // past the desired range, we will truncate the token stream. if (l.checkTruncateTokenRange(tokenRange)) { return l.tokens; } switch (r.data) { case ' ': case '\t': case '\r': case '\n': l.addWhitespaceFodder(); continue case '{': l.emitToken("TokenBraceL"); break; case '}': l.emitToken("TokenBraceR"); break; case '[': l.emitToken("TokenBracketL"); break; case ']': l.emitToken("TokenBracketR"); break; case ',': l.emitToken("TokenComma"); break; case '.': l.emitToken("TokenDot"); break; case '(': l.emitToken("TokenParenL"); break; case ')': l.emitToken("TokenParenR"); break; case ';': l.emitToken("TokenSemicolon"); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { l.backup(); err = l.lexNumber(); if (err != null) { return err; } break; } // String literals case '"': { const stringStartLoc = l.prevLocation(); // Don't include the quotes in the token data l.resetTokenStart(); for (r = l.next(); ; r = l.next()) { if (r.codePoint == LexEOF.codePoint) { return lexical.MakeStaticErrorPoint( "Unterminated String", l.fileName, stringStartLoc); } if (r.data === '"') { l.backup(); l.emitToken("TokenStringDouble"); /*_ =*/ l.next(); l.resetTokenStart(); break; } if (r.data === '\\' && l.peek().codePoint != LexEOF.codePoint) { r = l.next(); } } break; } case '\'': { const stringStartLoc = l.prevLocation(); l.resetTokenStart(); // Don't include the quotes in the token data for (r = l.next(); ; r = l.next()) { if (r.codePoint == LexEOF.codePoint) { return lexical.MakeStaticErrorPoint( "Unterminated String", l.fileName, stringStartLoc); } if (r.data === '\'') { l.backup(); l.emitToken("TokenStringSingle"); r = l.next(); l.resetTokenStart(); break; } if (r.data === '\\' && l.peek().codePoint != LexEOF.codePoint) { r = l.next(); } } break; } case '#': { l.resetTokenStart(); // Throw out the leading # for (r = l.next(); r.codePoint != LexEOF.codePoint && r.data !== '\n'; r = l.next()) { } // Leave the '\n' in the lexer to be fodder for the next round l.backup(); l.emitToken("TokenCommentHash"); break; } default: { if (isIdentifierFirst(r)) { l.backup(); l.lexIdentifier(); } else if (isSymbol(r)) { l.backup(); err = l.lexSymbol() if (err != null) { return err; } } else { return lexical.MakeStaticErrorPoint( `Could not lex the character '${r.data}'`, l.fileName, l.prevLocation()); } break; } } } // We are currently at the EOF. Emit a special token to capture any // trailing fodder l.emitToken("TokenEndOfFile") return l.tokens; }
the_stack
const portscanner = require('portscanner'); import * as fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; import * as crypto from 'crypto'; import axios from 'axios'; import * as cp from 'child_process'; import * as util from 'util'; const execAsync = util.promisify(cp.exec); import * as SharedConstants from './SharedConstants'; import { Settings } from './Settings'; import { StorageConnectionSettings } from "./StorageConnectionSettings"; import { ConnStringUtils } from './ConnStringUtils'; // Responsible for running the backend process export class BackendProcess { constructor(private _binariesFolder: string, private _storageConnectionSettings: StorageConnectionSettings, private _removeMyselfFromList: () => void, private _log: (l: string) => void) { } // Underlying Storage Connection Strings get storageConnectionStrings(): string[] { return this._storageConnectionSettings.storageConnStrings; } // Information about the started backend (if it was successfully started) get backendUrl(): string { return this._backendUrl; } // Folder where backend is run from (might be different, if the backend needs to be published first) get binariesFolder(): string { return this._eventualBinariesFolder; } // Kills the pending backend process async cleanup(): Promise<any> { this._backendPromise = null; this._backendUrl = ''; if (!this._funcProcess) { return; } console.log('Killing func process...'); this._funcProcess.kill(); this._funcProcess = null; } get backendCommunicationNonce(): string { return this._backendCommunicationNonce; } // Ensures that the backend is running (starts it, if needed) and returns its properties getBackend(): Promise<void> { if (!this._backendPromise) { this._backendPromise = this.getBackendAsync(); } return this._backendPromise; } // Reference to the shell instance running func.exe private _funcProcess: cp.ChildProcess | null = null; // Promise that resolves when the backend is started successfully private _backendPromise: Promise<void> | null = null; // Information about the started backend (if it was successfully started) private _backendUrl: string = ''; // Folder where backend is run from (might be different, if the backend needs to be published first) private _eventualBinariesFolder: string = this._binariesFolder; // A nonce for communicating with the backend private _backendCommunicationNonce = crypto.randomBytes(64).toString('base64'); // Path to Functions host private static _funcExePath: string = ''; // Prepares a set of environment variables for the backend process private getEnvVariables(): {} { // Important to inherit the context from VsCode, so that globally installed tools can be found const env = process.env; env[SharedConstants.NonceEnvironmentVariableName] = this._backendCommunicationNonce; // Also setting AzureWebJobsSecretStorageType to 'files', so that the backend doesn't need Azure Storage env['AzureWebJobsSecretStorageType'] = 'files'; delete env['AzureWebJobsStorage']; delete env['AzureWebJobsStorage__accountName']; delete env[SharedConstants.MsSqlConnStringEnvironmentVariableName]; if (this._storageConnectionSettings.isMsSql) { env[SharedConstants.MsSqlConnStringEnvironmentVariableName] = this._storageConnectionSettings.storageConnStrings[0]; // For MSSQL just need to set DFM_HUB_NAME to something, doesn't matter what it is so far env[SharedConstants.HubNameEnvironmentVariableName] = this._storageConnectionSettings.hubName; } else { // Need to unset this, in case it was set previously delete env[SharedConstants.HubNameEnvironmentVariableName]; if (!!this._storageConnectionSettings.isIdentityBasedConnection) { const storageAccountName = ConnStringUtils.GetAccountName(this._storageConnectionSettings.storageConnStrings[0]); env['AzureWebJobsStorage__accountName'] = storageAccountName; } else { env['AzureWebJobsStorage'] = this._storageConnectionSettings.storageConnStrings[0]; } } return env; } // Runs the backend Function instance on some port private startBackendOnPort(funcExePath: string, portNr: number, backendUrl: string, cancelToken: vscode.CancellationToken): Promise<void> { return new Promise<void>((resolve, reject) => { this._log(`Using Functions host: ${funcExePath}\n`); this._log(`Attempting to start the backend from ${this._binariesFolder} on ${backendUrl}...`); if (!fs.existsSync(this._binariesFolder)) { reject(`Couldn't find backend binaries in ${this._binariesFolder}`); return; } // If this is a source code project if (fs.readdirSync(this._binariesFolder).some(fn => fn.toLowerCase().endsWith('.csproj'))) { const publishFolder = path.join(this._binariesFolder, 'publish'); // if it wasn't published yet if (!fs.existsSync(publishFolder)) { // publishing it const publishProcess = cp.spawnSync('dotnet', ['publish', '-o', publishFolder], { cwd: this._binariesFolder, encoding: 'utf8' } ); if (!!publishProcess.stdout) { this._log(publishProcess.stdout.toString()); } if (publishProcess.status !== 0) { const err = 'dotnet publish failed. ' + (!!publishProcess.stderr ? publishProcess.stderr.toString() : `status: ${publishProcess.status}`); this._log(`ERROR: ${err}`); reject(err); return; } } this._eventualBinariesFolder = publishFolder; } this._funcProcess = cp.spawn(funcExePath, ['start', '--port', portNr.toString(), '--csharp'], { cwd: this._eventualBinariesFolder, env: this.getEnvVariables() }); this._funcProcess.stdout?.on('data', (data) => { const msg = data.toString(); this._log(msg); if (msg.toLowerCase().includes('no valid combination of account information found')) { reject('The provided Storage Connection String and/or Hub Name seem to be invalid.'); } }); this._funcProcess!.stderr?.on('data', (data) => { const msg = data.toString(); this._log(`ERROR: ${msg}`); reject(`Func: ${msg}`); }); console.log(`Waiting for ${backendUrl} to respond...`); // Waiting for the backend to be ready const timeoutInSeconds = Settings().backendTimeoutInSeconds; const intervalInMs = 500, numOfTries = timeoutInSeconds * 1000 / intervalInMs; var i = numOfTries; const intervalToken = setInterval(() => { const headers: any = {}; headers[SharedConstants.NonceHeaderName] = this._backendCommunicationNonce; // Pinging the backend and returning its URL when ready axios.get(`${backendUrl}/--${this._storageConnectionSettings.hubName}/about`, { headers }).then(response => { console.log(`The backend is now running on ${backendUrl}`); clearInterval(intervalToken); this._backendUrl = backendUrl; resolve(); }, err => { if (!!err.response && err.response.status === 401) { // This typically happens when mistyping Task Hub name clearInterval(intervalToken); reject(err.message); } }); if (cancelToken.isCancellationRequested) { clearInterval(intervalToken); reject(`Cancelled by the user`); } else if (--i <= 0) { console.log(`Timed out waiting for the backend!`); clearInterval(intervalToken); reject(`No response within ${timeoutInSeconds} seconds. Ensure you have the latest Azure Functions Core Tools installed globally.`); } }, intervalInMs); }); } private async getBackendAsync(): Promise<void> { const progressOptions = { location: vscode.ProgressLocation.Notification, title: `Starting the backend `, cancellable: true }; await vscode.window.withProgress(progressOptions, async (progress, token) => { try { const funcExePath = await this.getFuncExePath(); // Starting the backend on a first available port const portNr = await portscanner.findAPortNotInUse(37072, 38000); const backendUrl = Settings().backendBaseUrl.replace('{portNr}', portNr.toString()); progress.report({ message: backendUrl }); // Now running func.exe in backend folder await this.startBackendOnPort(funcExePath, portNr, backendUrl, token) } catch (err) { // This call is important, without it a typo in connString would persist until vsCode restart this._removeMyselfFromList(); throw err; } }); } private async getFuncExePath(): Promise<string> { if (!!BackendProcess._funcExePath) { return BackendProcess._funcExePath; } if (!!Settings().customPathToAzureFunctionsHost) { BackendProcess._funcExePath = Settings().customPathToAzureFunctionsHost; return BackendProcess._funcExePath; } // trying to detect the npm global package folder var npmGlobalFolder = ''; try { const npmListResult = await execAsync(`npm list -g --depth=0`); npmGlobalFolder = npmListResult .stdout .split('\n')[0]; } catch (err) { this._log(`npm list -g failed. ${!(err as any).message ? err : (err as any).message}`) } if (!!npmGlobalFolder) { // Trying C:\Users\username\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin var globalFuncPath = path.join(npmGlobalFolder, `node_modules`, `azure-functions-core-tools`, `bin`, `func.exe`); if (!!fs.existsSync(globalFuncPath)) { BackendProcess._funcExePath = globalFuncPath; return BackendProcess._funcExePath; } globalFuncPath = path.join(npmGlobalFolder, `node_modules`, `azure-functions-core-tools`, `bin`, `func`); if (!!fs.existsSync(globalFuncPath)) { BackendProcess._funcExePath = globalFuncPath; return BackendProcess._funcExePath; } } // Trying C:\Program Files\Microsoft\Azure Functions Core Tools globalFuncPath = path.resolve(process.env.programfiles ?? '', 'Microsoft', 'Azure Functions Core Tools', 'func.exe'); if (!!fs.existsSync(globalFuncPath)) { BackendProcess._funcExePath = globalFuncPath; return BackendProcess._funcExePath; } // Trying yarn global bin var yarnGlobalFolder = ''; try { const yarnGlobalBinResult = await execAsync(`yarn global bin`); yarnGlobalFolder = yarnGlobalBinResult .stdout .split('\n')[0]; } catch (err) { this._log(`yarn global bin failed. ${!(err as any).message ? err : (err as any).message}`) } if (!!yarnGlobalFolder) { var globalFuncPath = path.join(yarnGlobalFolder, `func.exe`); if (!!fs.existsSync(globalFuncPath)) { BackendProcess._funcExePath = globalFuncPath; return BackendProcess._funcExePath; } globalFuncPath = path.join(yarnGlobalFolder, process.platform === 'win32' ? `func.cmd` : `func`); if (!!fs.existsSync(globalFuncPath)) { BackendProcess._funcExePath = globalFuncPath; return BackendProcess._funcExePath; } } // Defaulting to 'func' command, hopefully it will be properly resolved BackendProcess._funcExePath = 'func'; return BackendProcess._funcExePath; } }
the_stack
import { FetchableType } from "./Fetchable"; import { FieldOptionsValue } from "./FieldOptions"; import { ParameterRef } from "./Parameter"; import { TextWriter } from "./TextWriter"; export interface Fetcher<E extends string, T extends object, TVariables extends object> { readonly fetchableType: FetchableType<E>; readonly fieldMap: ReadonlyMap<string, FetcherField>; readonly directiveMap: ReadonlyMap<string, DirectiveArgs>; findField(fieldName: string): FetcherField | undefined; toString(): string; toFragmentString(): string; toJSON(): string; // for recoil variableTypeMap: ReadonlyMap<string, string>; " $supressWarnings"(_1: T, _2: TVariables): never; } export interface ObjectFetcher<E extends string, T extends object, TVariables extends object> extends Fetcher<E, T, TVariables> { readonly " $category": "OBJECT"; } export interface ConnectionFetcher<E extends string, T extends object, TVariables extends object> extends Fetcher<E, T, TVariables> { readonly " $category": "CONNECTION"; } export interface EdgeFetcher<E extends string, T extends object, TVariables extends object> extends Fetcher<E, T, TVariables> { readonly " $category": "EDGE"; } export type ModelType<F> = F extends Fetcher<string, infer M, object> ? M : F extends ObjectFetcher<string, infer M, object> ? M : F extends ConnectionFetcher<string, infer M, object> ? M : F extends EdgeFetcher<string, infer M, object> ? M : never ; export abstract class AbstractFetcher<E extends string, T extends object, TVariables extends object> implements Fetcher<E, T, TVariables> { private _fetchableType: FetchableType<E>; private _unionItemTypes?: string[]; private _prev?: AbstractFetcher<string, object, object>; private _fieldMap?: ReadonlyMap<string, FetcherField>; private _directiveMap: ReadonlyMap<string, DirectiveArgs>; private _result: Result; constructor( ctx: AbstractFetcher<string, object, object> | [FetchableType<E>, string[] | undefined], private _negative: boolean, private _field: string, private _args?: {[key: string]: any}, private _child?: AbstractFetcher<string, object, object>, private _fieldOptionsValue?: FieldOptionsValue, private _directive?: string, private _directiveArgs?: DirectiveArgs ) { if (Array.isArray(ctx)) { this._fetchableType = ctx[0]; this._unionItemTypes = ctx[1] !== undefined && ctx[1].length !== 0 ? ctx[1] : undefined; } else { this._fetchableType = ctx._fetchableType as FetchableType<E>; this._unionItemTypes = ctx._unionItemTypes; this._prev = ctx; } } get fetchableType(): FetchableType<E> { return this._fetchableType; } protected addField<F extends AbstractFetcher<string, object, object>>( field: string, args?: {[key: string]: any}, child?: AbstractFetcher<string, object, object>, optionsValue?: FieldOptionsValue ): F { return this.createFetcher( false, field, args, child, optionsValue ) as F; } protected removeField<F extends AbstractFetcher<string, object, object>>(field: string): F { if (field === '__typename') { throw new Error("__typename cannot be removed"); } return this.createFetcher( true, field ) as F; } protected addEmbbeddable<F extends AbstractFetcher<string, object, object>>( child: AbstractFetcher<string, object, object>, fragmentName?: string ): F { let fieldName: string; if (fragmentName !== undefined) { if (fragmentName.length === 0) { throw new Error("fragmentName cannot be ''"); } if (fragmentName.startsWith("on ")) { throw new Error("fragmentName cannot start with 'on '"); } fieldName = `... ${fragmentName}`; } else if (child._fetchableType.name === this._fetchableType.name || child._unionItemTypes !== undefined) { fieldName = '...'; } else { fieldName = `... on ${child._fetchableType.name}`; } return this.createFetcher( false, fieldName, undefined, child ) as F; } protected addDirective<F extends AbstractFetcher<string, object, object>>( directive: string, directiveArgs?: DirectiveArgs ): F { return this.createFetcher( false, "", undefined, undefined, undefined, directive, directiveArgs ) as F; } protected abstract createFetcher( negative: boolean, field: string, args?: {[key: string]: any}, child?: AbstractFetcher<string, object, object>, optionsValue?: FieldOptionsValue, directive?: string, directiveArgs?: object ): AbstractFetcher<string, object, object>; get fieldMap(): ReadonlyMap<string, FetcherField> { let m = this._fieldMap; if (m === undefined) { this._fieldMap = m = this._getFieldMap0(); } return m; } private _getFieldMap0(): ReadonlyMap<string, FetcherField> { const fetchers: AbstractFetcher<string, object, object>[] = []; for (let fetcher: AbstractFetcher<string, object, object> | undefined = this; fetcher !== undefined; fetcher = fetcher._prev ) { if (fetcher._field !== "") { fetchers.push(fetcher); } } const fieldMap = new Map<string, FetcherField>(); for (let i = fetchers.length - 1; i >= 0; --i) { const fetcher = fetchers[i]; if (fetcher._field.startsWith('...')) { let childFetchers = fieldMap.get(fetcher._field)?.childFetchers as AbstractFetcher<string, object, object>[]; if (childFetchers === undefined) { childFetchers = []; fieldMap.set(fetcher._field, { plural: false, childFetchers }); // Fragment cause mutliple child fetchers } childFetchers.push(fetcher._child!); } else { if (fetcher._negative) { fieldMap.delete(fetcher._field); } else { fieldMap.set(fetcher._field, { argGraphQLTypes: fetcher.fetchableType.fields.get(fetcher._field)?.argGraphQLTypeMap, args: fetcher._args, fieldOptionsValue: fetcher._fieldOptionsValue, plural: fetcher.fetchableType.fields.get(fetcher._field)?.isPlural ?? false, childFetchers: fetcher._child === undefined ? undefined: [fetcher._child] // Association only cause one child fetcher }); } } } return fieldMap; } get directiveMap(): ReadonlyMap<string, DirectiveArgs> { let map = this._directiveMap; if (map === undefined) { this._directiveMap = map = this._getDirectiveMap(); } return map; } private _getDirectiveMap(): ReadonlyMap<string, DirectiveArgs> { const map = new Map<string, DirectiveArgs>(); for (let fetcher: AbstractFetcher<string, object, object> | undefined = this; fetcher !== undefined; fetcher = fetcher._prev ) { if (fetcher._directive !== undefined) { if (!map.has(fetcher._directive)) { map.set(fetcher._directive, fetcher._directiveArgs); } } } return map; } get variableTypeMap(): ReadonlyMap<string, string> { return this.result.variableTypeMap; } findField(fieldName: string): FetcherField | undefined { const field = this.fieldMap.get(fieldName); if (field !== undefined) { return field; } for (const [fieldName, field] of this.fieldMap) { if (fieldName.startsWith("...") && field.childFetchers !== undefined) { for (const fragmentFetcher of field.childFetchers) { const deeperField = fragmentFetcher.findField(fieldName); if (deeperField !== undefined) { return deeperField; } } } } return undefined; } toString(): string { return this.result.text; } toFragmentString(): string { return this.result.fragmentText; } toJSON(): string { return JSON.stringify(this.result); } private get result(): Result { let r = this._result; if (r === undefined) { this._result = r = this.createResult(); } return r; } private createResult(): Result { const writer = new TextWriter(); const fragmentWriter = new TextWriter(); let ctx = new ResultContext(writer); ctx.acceptDirectives(this.directiveMap); writer.scope({type: "BLOCK", multiLines: true, suffix: '\n'}, () => { ctx.accept(this); }); const renderedFragmentNames = new Set<string>(); while (true) { const fragmentMap = ctx.namedFragmentMap; if (fragmentMap.size === 0) { break; } ctx = new ResultContext(fragmentWriter, ctx); for (const [fragmentName, fragment] of fragmentMap) { if (renderedFragmentNames.add(fragmentName)) { fragmentWriter.text(`fragment ${fragmentName} on ${fragment.fetchableType.name} `); ctx.acceptDirectives(fragment.directiveMap); fragmentWriter.scope({type: "BLOCK", multiLines: true, suffix: '\n'}, () => { ctx.accept(fragment); }); } } } return { text: writer.toString(), fragmentText: fragmentWriter.toString(), variableTypeMap: ctx.variableTypeMap }; } " $supressWarnings"(_: T, _2: TVariables): never { throw new Error("' $supressWarnings' is not supported"); } } export interface FetcherField { readonly argGraphQLTypes?: ReadonlyMap<string, string>; readonly args?: object; readonly fieldOptionsValue?: FieldOptionsValue; readonly plural: boolean; readonly childFetchers?: ReadonlyArray<AbstractFetcher<string, object, object>>; } export abstract class SpreadFragment<TFragmentName extends string, E extends string, T extends object, TVariables extends object> { readonly " $__instanceOfSpreadFragment" = true; protected constructor(readonly name: TFragmentName, readonly fetcher: Fetcher<E, T, TVariables>) {} } export type DirectiveArgs = { readonly [key: string]: ParameterRef<string> | StringValue | any; } | undefined; export class StringValue { constructor( readonly value: any, readonly quotationMarks: boolean = true ) { } } interface Result { readonly text: string; readonly fragmentText: string; readonly variableTypeMap: ReadonlyMap<string, string>; } class ResultContext { readonly namedFragmentMap = new Map<string, Fetcher<string, object, object>>(); readonly variableTypeMap: Map<string, string>; constructor( private readonly writer: TextWriter = new TextWriter(), ctx?: ResultContext ) { this.variableTypeMap = ctx?.variableTypeMap ?? new Map<string, string>(); } accept(fetcher: Fetcher<string, object, object>) { const t = this.writer.text.bind(this.writer); for (const [fieldName, field] of fetcher.fieldMap) { if (fieldName !== "...") { // Inline fragment const alias = field.fieldOptionsValue?.alias; if (alias !== undefined && alias !== "" && alias !== fieldName) { t(`${alias}: `); } t(fieldName); if (field.argGraphQLTypes !== undefined) { this.acceptArgs(field.args, field.argGraphQLTypes); } this.acceptDirectives(field.fieldOptionsValue?.directives); } const childFetchers = field.childFetchers; if (childFetchers !== undefined && childFetchers.length !== 0) { if (fieldName === "...") { for (const childFetcher of childFetchers) { this.accept(childFetcher); } } else if (fieldName.startsWith("...") && !fieldName.startsWith("... on ")) { const fragmentName = fieldName.substring("...".length).trim(); const oldFragment = this.namedFragmentMap.get(fragmentName); for (const childFetcher of childFetchers) { if (oldFragment !== undefined && oldFragment !== childFetcher) { throw new Error(`Conflict fragment name ${fragmentName}`); } this.namedFragmentMap.set(fragmentName, childFetcher); } } else { t(' '); this.writer.scope({type: "BLOCK", multiLines: true}, () => { for (const childFetcher of childFetchers) { this.accept(childFetcher); } }); } } t('\n'); } } acceptDirectives(directives?: ReadonlyMap<string, DirectiveArgs>) { if (directives !== undefined) { for (const [directive, args] of directives) { this.writer.text(`\n@${directive}`); this.acceptArgs(args); } } } private acceptArgs( args?: object, argGraphQLTypeMap?: ReadonlyMap<string, string> // undefined: directive args; otherwise: field args ) { if (args === undefined) { return; } const t = this.writer.text.bind(this.writer); let hasField: boolean; if (argGraphQLTypeMap !== undefined) { hasField = false; for (const argName in args) { const argGraphQLTypeName = argGraphQLTypeMap.get(argName); if (argGraphQLTypeName !== undefined) { hasField = true; break; } else { console.warn(`Unexpected argument: ${argName}`); } } } else { hasField = Object.keys(args).length !== 0; } if (hasField) { this.writer.scope({type: "ARGUMENTS", multiLines: isMultLineJSON(args)}, () => { for (const argName in args) { this.writer.seperator(); const arg = args[argName]; let argGraphQLTypeName: string | undefined; if (argGraphQLTypeMap !== undefined) { argGraphQLTypeName = argGraphQLTypeMap.get(argName); if (argGraphQLTypeName !== undefined) { if (arg[" $__instanceOfParameterRef"]) { const parameterRef = arg as ParameterRef<string>; if (parameterRef.graphqlTypeName !== undefined && parameterRef.graphqlTypeName !== argGraphQLTypeName) { throw new Error( `Argument '${parameterRef.name}' has conflict type, the type of paremter '${argName}' is '${argGraphQLTypeName}' ` + `but the graphqlTypeName of ParameterRef is '${parameterRef.graphqlTypeName}'` ); } const registeredType = this.variableTypeMap.get(parameterRef.name); if (registeredType !== undefined && registeredType !== argGraphQLTypeName) { throw new Error( `Argument '${parameterRef.name}' has conflict type, it's typed has been specified twice, ` + `one as '${registeredType}' and one as '${argGraphQLTypeName}'` ); } this.variableTypeMap.set(parameterRef.name, argGraphQLTypeName); t(`${argName}: $${parameterRef.name}`); } else { t(`${argName}: `); this.acceptLiteral(arg); } } else { throw new Error(`Unknown argument '${argName}'`); } } else { if (arg[" $__instanceOfParameterRef"]) { const parameterRef = arg as ParameterRef<string>; if (parameterRef.graphqlTypeName === undefined) { throw new Error(`The graphqlTypeName of directive argument '${parameterRef.name}' is not specifed`); } this.variableTypeMap.set(parameterRef.name, parameterRef.graphqlTypeName); t(`${argName}: $${parameterRef.name}`); } else { t(`${argName}: `); this.acceptLiteral(arg); } } } }); } } private acceptLiteral(value: any) { const t = this.writer.text.bind(this.writer); if (value === undefined || value === null) { t("null"); } else if (typeof value === 'number') { t(value.toString()); } else if (typeof value === 'string') { t(`"${value.replace('"', '\\"')}"`); } else if (typeof value === 'boolean') { t(value ? "true" : "false"); } else if (value instanceof StringValue) { if (value.quotationMarks) { t(`"${value.value.replace('"', '\\"')}"`); } else { t(value.value); } } else if (Array.isArray(value) || value instanceof Set) { this.writer.scope({type: "ARRAY"}, () => { for (const e of value) { this.writer.seperator(); this.acceptLiteral(e); } }); } else if (value instanceof Map) { for (const [k, v] of value) { this.writer.seperator(); this.acceptMapKey(k); t(": "); this.acceptLiteral(v); } } else if (typeof value === 'object') { for (const k in value) { this.writer.seperator(); this.acceptMapKey(k); t(": "); this.acceptLiteral(value[k]); } } } private acceptMapKey(key: any) { if (typeof key === "string") { this.writer.text(`"${key.replace('"', '\\"')}"`); } else if (typeof key === "number") { this.writer.text("${key}"); } else { throw new Error(`Unsupported map key ${key}`); } } } function isMultLineJSON(obj: any): boolean { let size = 0; if (Array.isArray(obj)) { for (const value of obj) { if (typeof value === 'object' && !value[" $__instanceOfParameterRef"]) { return true; } if (++size > 2) { return true; } } } else if (typeof obj === 'object') { for (const key in obj) { const value = obj[key]; if (typeof value === 'object' && !value[" $__instanceOfParameterRef"]) { return true; } if (++size > 2) { return true; } } } return false; }
the_stack
"use strict"; import * as fse from "fs-extra"; import * as os from "os"; import * as path from "path"; import * as vscode from "vscode"; import * as zlib from "zlib"; import { AcrManager } from "../common/acrManager"; import { Constants } from "../common/constants"; import { RequirementsChecker } from "../common/requirementsChecker"; import { TelemetryClient } from "../common/telemetryClient"; import { Utility } from "../common/utility"; type ProgressUpdater = vscode.Progress<{ message?: string; increment?: number }>; type PartialProgressOptions = Partial<vscode.ProgressOptions>; interface IUserProgressOptions extends PartialProgressOptions { isUserInitiated?: boolean; cancellationToken?: vscode.CancellationToken; } const defaultProgressOptions: vscode.ProgressOptions = { location: vscode.ProgressLocation.Notification, title: Constants.openEnclaveDisplayName, }; const userProgressOptionsDefaults: IUserProgressOptions = { ...defaultProgressOptions, isUserInitiated: true, cancellationToken: undefined, }; export class OpenEnclaveManager { private _context: vscode.ExtensionContext; constructor(context: vscode.ExtensionContext) { this._context = context; } public async createOpenEnclaveSolution(outputChannel: vscode.OutputChannel): Promise<void> { return this.promiseWithProgress(async (progress, resolve, reject) => { return this.internalCreateOpenEnclaveSolution(outputChannel, progress) .then(() => { resolve(); }) .catch((err) => { reject(err); }); }); } public async checkRequirements(outputChannel: vscode.OutputChannel): Promise<void> { return this.promiseWithProgress(async (progress, resolve, reject) => { return RequirementsChecker.checkRequirements(true, true) .then(() => { resolve(); }) .catch((err) => { reject(err); }); }); } private getEmbeddedDevKitTarballPath(): string { return this._context.asAbsolutePath(path.join(Constants.assetsFolder, Constants.devKitFolder, Constants.devKitTarball)); } private async internalCreateOpenEnclaveSolution(outputChannel: vscode.OutputChannel, progress: ProgressUpdater): Promise<void> { return new Promise(async (resolve, reject) => { // Prompt user for new Solution path const parentPath: string | undefined = await this.getSolutionParentFolder(); if (parentPath === undefined) { reject(); } else { try { // Populate new solution folder with Open Enclave code const openEnclaveFolder = await this.populateOpenEnclaveSolution(parentPath, outputChannel, progress); resolve(); // Open new solution in VSCode await vscode.commands.executeCommand("vscode.openFolder", vscode.Uri.file(openEnclaveFolder), false); } catch (error) { reject(error); } } }); } private async populateOpenEnclaveSolution(parentFolder: string, outputChannel: vscode.OutputChannel, progress: ProgressUpdater): Promise<string> { return new Promise(async (resolve, reject) => { try { // Determine what style of project to create (standalone | edge-container) // Note: this is only a choice on Linux, otherwise, only edge-container is available. let createEdgeSolution = true; let dockerRepo: string | undefined; if (os.platform() === "linux") { const oeProjectStyle = await Utility.showQuickPick([Constants.standaloneProjectType, Constants.edgeProjectType], Constants.selectProjectType); createEdgeSolution = (oeProjectStyle === Constants.edgeProjectType); } TelemetryClient.sendEvent(`msiot-vscode-openenclave.newSolution.${createEdgeSolution ? "edge" : "standalone"}`); // Prompt user for solution name const openEnclaveName: string | undefined = await this.inputSolutionName(parentFolder, (createEdgeSolution) ? Constants.edgeSolutionNameDefault : Constants.standaloneSolutionNameDefault); if (openEnclaveName === undefined) { reject(); return ""; } // Prompt user for docker repo if needed if (createEdgeSolution) { const dftValue: string = `localhost:5000/${openEnclaveName.toLowerCase()}`; dockerRepo = await Utility.showInputBox(Constants.repositoryPattern, Constants.providerDockerRepository, undefined, dftValue); } // Get Solution Path const openEnclaveFolder: string = path.join(parentFolder, openEnclaveName); await fse.mkdirsSync(openEnclaveFolder); // Create new UUID for solution const uuidv4 = require("uuid/v4"); const uuid: string = uuidv4(); // Create shared/non-Shared build and sdk folders const devkitFolder = path.join(openEnclaveFolder, Constants.devKitFolder); const sdkFolder = path.join(openEnclaveFolder, Constants.thirdPartyFolder, Constants.openEnclaveSdkName); const buildFolder = path.join(openEnclaveFolder, Constants.standaloneBuildFolder); // Create map of template replacements (i.e. [[XXX]] => yyy) const replacementMap: Map<string, string> = this.setupTemplateReplacementMap(openEnclaveFolder, openEnclaveName, sdkFolder, devkitFolder, buildFolder, uuid, dockerRepo); const enclaveFolder = (createEdgeSolution) ? path.join(openEnclaveFolder, Constants.edgeModulesFolder, openEnclaveName) : openEnclaveFolder; await fse.mkdirsSync(enclaveFolder); // Create user files with template replacements made this.progressAndOutput("Creating base files", progress, outputChannel); // Put base files in place const baseTemplateSolutionPath = this._context.asAbsolutePath(path.join(Constants.assetsFolder, Constants.baseSolutionTemplateFolder)); await Utility.copyTemplateFiles(baseTemplateSolutionPath, enclaveFolder, null, replacementMap); this.progressAndOutput("Base files created", progress, outputChannel); if (createEdgeSolution) { this.progressAndOutput("Creating edge files", progress, outputChannel); // Put edge files in place const edgeTemplateSolutionPath = this._context.asAbsolutePath(path.join(Constants.assetsFolder, Constants.edgeSolutionTemplateFolder)); await Utility.copyTemplateFiles(edgeTemplateSolutionPath, openEnclaveFolder, null, replacementMap); } else { this.progressAndOutput("Creating standalone files", progress, outputChannel); // Put standalone files in place const standaloneTemplateSolutionPath = this._context.asAbsolutePath(path.join(Constants.assetsFolder, Constants.standaloneSolutionTemplateFolder)); await Utility.copyTemplateFiles(standaloneTemplateSolutionPath, openEnclaveFolder, null, replacementMap); } if (createEdgeSolution) { if (dockerRepo) { this.progressAndOutput("Updating deployment template", progress, outputChannel); const address = Utility.getRegistryAddress(dockerRepo); const addressKey = Utility.getAddressKey(address); const lowerCase = address.toLowerCase(); if (lowerCase !== "mcr.microsoft.com" && lowerCase !== "localhost" && !lowerCase.startsWith("localhost:")) { await this.writeRegistryCredEnv(address, path.join(openEnclaveFolder, ".env"), `${addressKey}_USERNAME`, `${addressKey}_PASSWORD`); await this.internalUpdateDeploymentTemplate(openEnclaveFolder, address, addressKey, `${addressKey}_USERNAME`, `${addressKey}_PASSWORD`); } } } else { // Ensure that the build folders are created for the standalone project this.progressAndOutput("Creating build folders", progress, outputChannel); await fse.mkdirsSync(path.join(openEnclaveFolder, Constants.standaloneBuildFolder, "sgx")); await fse.mkdirsSync(path.join(openEnclaveFolder, Constants.standaloneBuildFolder, "vexpress-qemu_armv8a")); await fse.mkdirsSync(path.join(openEnclaveFolder, Constants.standaloneBuildFolder, "ls-ls1012grapeboard")); } // Ensure that the devkit is present on the system const sharedDevkitLocation = path.join(this._context.globalStoragePath, Constants.DevKitVersion, Constants.devKitFolder); if (!fse.existsSync(sharedDevkitLocation)) { const embeddedDevkitPath = this.getEmbeddedDevKitTarballPath(); this.progressAndOutput("Expanding platform devkit (this is infrequent)", progress, outputChannel); await this.internalExpandDevkit(fse.createReadStream(embeddedDevkitPath), sharedDevkitLocation, progress, outputChannel); } // Ensure that the devkit is present in the project this.progressAndOutput("Adding devkit to solution", progress, outputChannel); await this.internalMakeCopyOrLink(sharedDevkitLocation, path.join(enclaveFolder, Constants.devKitFolder), !createEdgeSolution); // Success! this.progressAndOutput("Created Open Enclave solution", progress, outputChannel); resolve(openEnclaveFolder); } catch (error) { TelemetryClient.sendEvent(`msiot-vscode-openenclave.newSolution.Failure`, {error: (error) ? error.message : "unknown"}); this.progressAndOutput("Failed to create new Open Enclave solution", progress, outputChannel); reject(error); } }); } private async writeRegistryCredEnv(address: string, envFile: string, usernameEnv: string, passwordEnv: string, debugUsernameEnv?: string, debugPasswordEnv?: string): Promise<void> { if (!usernameEnv) { return; } if (address.endsWith(".azurecr.io")) { await this.populateAcrCredential(address, envFile, usernameEnv, passwordEnv, debugUsernameEnv, debugPasswordEnv); } else { await this.populateStaticEnv(envFile, usernameEnv, passwordEnv, debugUsernameEnv, debugPasswordEnv); } } private async populateStaticEnv(envFile: string, usernameEnv: string, passwordEnv: string, debugUsernameEnv?: string, debugPasswordEnv?: string): Promise<void> { let envContent = `\n${usernameEnv}=\n${passwordEnv}=\n`; if (debugUsernameEnv && debugUsernameEnv !== usernameEnv) { envContent = `\n${envContent}${debugUsernameEnv}=\n${debugPasswordEnv}=\n`; } await fse.ensureFile(envFile); await fse.appendFile(envFile, envContent, { encoding: "utf8" }); this.askEditEnv(envFile); } private async populateAcrCredential(address: string, envFile: string, usernameEnv: string, passwordEnv: string, debugUsernameEnv?: string, debugPasswordEnv?: string): Promise<void> { const acrManager = new AcrManager(); let cred; try { cred = await acrManager.getAcrRegistryCredential(address); } catch (err) { // tslint:disable-next-line:no-console console.error(err); } if (cred && cred.username !== undefined) { let envContent = `\n${usernameEnv}=${cred.username}\n${passwordEnv}=${cred.password}\n`; if (debugUsernameEnv && debugUsernameEnv !== usernameEnv) { envContent = `\n${envContent}${debugUsernameEnv}=${cred.username}\n${debugPasswordEnv}=${cred.password}\n`; } await fse.ensureFile(envFile); await fse.appendFile(envFile, envContent, { encoding: "utf8" }); vscode.window.showInformationMessage(Constants.acrEnvSet); } else { await this.populateStaticEnv(envFile, usernameEnv, passwordEnv, debugUsernameEnv, debugPasswordEnv); } } private async askEditEnv(envFile: string): Promise<void> { const yesOption = "Yes"; const option = await vscode.window.showInformationMessage(Constants.setRegistryEnvNotification, yesOption); if (option === yesOption) { await fse.ensureFile(envFile); await vscode.window.showTextDocument(vscode.Uri.file(envFile)); } } private async internalUpdateDeploymentTemplate(openEnclaveFolder: string, address: string, addressKey: string, usernameEnv: string, passwordEnv: string): Promise<void> { return new Promise<void>(async (resolve, reject) => { const lowerCase = address.toLowerCase(); if (lowerCase === "mcr.microsoft.com" || lowerCase === "localhost" || lowerCase.startsWith("localhost:")) { resolve(); } else { try { const filesAndDirs = await fse.readdir(openEnclaveFolder); await Promise.all( filesAndDirs.map(async (name) => { const templateFile = path.join(openEnclaveFolder, name); const stat: fse.Stats = await fse.stat(templateFile); if (stat.isFile()) { const matches = name.match(new RegExp(Constants.configDeploymentFilePattern)); if (matches && matches.length !== 0) { const templateContents = await fse.readFile(templateFile, "utf8"); const templateJson = JSON.parse(templateContents); const runtimeSettings = templateJson.modulesContent.$edgeAgent["properties.desired"].runtime.settings; const newRegistry = `{ "username": "$${usernameEnv}", "password": "$${passwordEnv}", "address": "${address}" }`; runtimeSettings.registryCredentials = {}; runtimeSettings.registryCredentials[addressKey] = JSON.parse(newRegistry); await fse.writeFile(templateFile, JSON.stringify(templateJson, null, 2), { encoding: "utf8" }); } } }), ); resolve(); } catch (error) { reject(error); } } }); } private internalMakeCopyOrLink(sharedLocation: string, localLocation: string, useSymLink: boolean): Promise<void> { return new Promise<void>((resolve, reject) => { try { if (useSymLink) { fse.symlinkSync(sharedLocation, localLocation); } else { fse.copySync(sharedLocation, localLocation); } resolve(); } catch (error) { reject(error); } }); } private internalMove(originalLocation: string, newLocation: string): Promise<void> { return new Promise<void>((resolve, reject) => { try { fse.moveSync(originalLocation, newLocation); resolve(); } catch (error) { reject(error); } }); } private async internalDownloadDevKitFromBlobStorage(progress: ProgressUpdater, outputChannel: vscode.OutputChannel): Promise<void> { return new Promise(async (resolve, reject) => { // Ensure that DevKit blob information is available const account = Constants.DevKitBlobAccount; const containerName = Constants.DevKitBlobContainerName; const blobName = Constants.DevKitBlobName; if (account === "" || containerName === "" || blobName === "") { reject("missing DevKit source"); } else { const storageAccountUri = "https://" + account + ".blob.core.windows.net"; // Download devkit from Azure Blob this.progressAndOutput("Downloading devkit", progress, outputChannel); const tmp = require("tmp"); return tmp.file({prefix: Constants.devKitFolder, postfix: ".tmp"}, async (err: Error, tempFilePath: string, fd: any, cleanupCallback: any) => { if (err) { reject(err); } else { const storage = require("azure-storage"); const blobService = storage.createBlobServiceAnonymous(storageAccountUri); blobService.getBlobToLocalFile(containerName, blobName, tempFilePath, async (blobErr: Error) => { if (blobErr) { reject(blobErr); } else { // Expand downloaded devkit tarball to local path this.progressAndOutput("Expanding devkit", progress, outputChannel); await this.internalExpandDevkit(fse.createReadStream(tempFilePath), null, progress, outputChannel); // Remove temp file await cleanupCallback(); resolve(); } }); } }); } }); } private async internalExpandDevkit(devKitStream: NodeJS.ReadableStream, incomingWorkspaceFolder: string | null, progress: ProgressUpdater, outputChannel: vscode.OutputChannel): Promise<void> { return new Promise(async (resolve, reject) => { const workspaceFolders = vscode.workspace.workspaceFolders; const workspaceFolder: string | undefined = (incomingWorkspaceFolder !== null) ? incomingWorkspaceFolder : (workspaceFolders && workspaceFolders.length > 0) ? path.join(workspaceFolders[0].uri.fsPath, Constants.devKitFolder) : undefined; if (workspaceFolder !== undefined) { fse.pathExists(workspaceFolder, (pathExistsErr: Error, exists: boolean) => { if (pathExistsErr) { reject(pathExistsErr); } else if (exists) { // If sdkDestination exists, it must be emptied and deleted. return this.clearFolderAndThen(workspaceFolder, resolve, reject, progress, outputChannel, () => { // Folder has been deleted, download SDK from git return this.expandTarGzStream(devKitStream, workspaceFolder, "Expanding shared devkit", progress, outputChannel) .then(() => { // Signal success resolve(); }) .catch((gitErr) => { // Signal git failure reject(gitErr); }); }); } else { // If folder does not exist, download SDK from git return this.expandTarGzStream(devKitStream, workspaceFolder, "Expanding shared devkit", progress, outputChannel) .then(() => { // Signal success resolve(); }) .catch((gitErr) => { // Signal git failure reject(gitErr); }); }}); } }); } private async expandTarGzStream(devKitStream: NodeJS.ReadableStream, localFilePath: string, progressPrefix: string, progress: ProgressUpdater, outputChannel: vscode.OutputChannel): Promise<void> { return new Promise(async (resolve, reject) => { this.progressAndOutput(`${progressPrefix}`, progress, outputChannel); fse.mkdirsSync(localFilePath); // Pipe: DevKit Stream => Zlib unizp => tar.extract const tar = require("tar"); return devKitStream .on("error", (err: Error) => { this.progressAndOutput(`${progressPrefix} failed`, progress, outputChannel); reject(err); }) .pipe(zlib.createGunzip()) .on("error", (err: Error) => { this.progressAndOutput(`${progressPrefix} failed`, progress, outputChannel); reject(err); }) .pipe(tar.extract({ cwd: localFilePath, strip: 0 })) .on("close", () => { this.progressAndOutput(`${progressPrefix} finished`, progress, outputChannel); resolve(); }) .on("error", (err: Error) => { this.progressAndOutput(`${progressPrefix} failed`, progress, outputChannel); reject(err); }); }); } private createUuidPart(uuid: string, start: number, end: number): string { const uuidPart = uuid.substring(start, end); return "0x" + uuidPart; } private setupTemplateReplacementMap( solutionFolder: string, solutionName: string, sdkFolder: string, devkitFolder: string, buildFolder: string, uuid: string, dockerRepo: string | undefined): Map<string, string> { // Create map of template replacements (i.e. [[XXX]] => yyy) const replacementMap: Map<string, string> = new Map<string, string>(); if (uuid.length !== 36 || uuid.charAt(8) !== "-" || uuid.charAt(13) !== "-" || uuid.charAt(18) !== "-" || uuid.charAt(23) !== "-") { throw new Error("invalid uuid: " + uuid); } // Add UUID and UUID parts to template replacement map replacementMap.set("[[generated-uuid]]", uuid); replacementMap.set("[[generated-uuid-part-1]]", this.createUuidPart(uuid, 0, 8)); replacementMap.set("[[generated-uuid-part-2]]", this.createUuidPart(uuid, 9, 13)); replacementMap.set("[[generated-uuid-part-3]]", this.createUuidPart(uuid, 14, 18)); replacementMap.set("[[generated-uuid-part-4-a]]", this.createUuidPart(uuid, 19, 21)); replacementMap.set("[[generated-uuid-part-4-b]]", this.createUuidPart(uuid, 21, 23)); replacementMap.set("[[generated-uuid-part-5-a]]", this.createUuidPart(uuid, 24, 26)); replacementMap.set("[[generated-uuid-part-5-b]]", this.createUuidPart(uuid, 26, 28)); replacementMap.set("[[generated-uuid-part-5-c]]", this.createUuidPart(uuid, 28, 30)); replacementMap.set("[[generated-uuid-part-5-d]]", this.createUuidPart(uuid, 30, 32)); replacementMap.set("[[generated-uuid-part-5-e]]", this.createUuidPart(uuid, 32, 34)); replacementMap.set("[[generated-uuid-part-5-f]]", this.createUuidPart(uuid, 34, 36)); // Add solution name to template replacement map replacementMap.set("[[project-name]]", solutionName); // Add devkit path to template replacement map const normalizedDevkitPath = devkitFolder.replace(new RegExp("\\\\", "g"), "/"); replacementMap.set("[[devkit-folder]]", normalizedDevkitPath); // Add solution path to template replacement map const normalizedSolutionPath = solutionFolder.replace(new RegExp("\\\\", "g"), "/"); replacementMap.set("[[solution-folder]]", normalizedSolutionPath); // Add sdk path to template replacement map const normalizedSdkPath = sdkFolder.replace(new RegExp("\\\\", "g"), "/"); replacementMap.set("[[sdk-folder]]", normalizedSdkPath); // Add build path to template replacement map const normalizedBuildPath = buildFolder.replace(new RegExp("\\\\", "g"), "/"); replacementMap.set("[[build-folder]]", normalizedBuildPath); // Add settings file name to template replacement map replacementMap.set("[[settings]]", "settings"); // If docker repo is provided, add it to map if (dockerRepo) { replacementMap.set("[[docker-repo]]", dockerRepo); const dockerRepoAddress = Utility.getRegistryAddress(dockerRepo); replacementMap.set("[[docker-repo-address]]", dockerRepoAddress); } return replacementMap; } private async getSolutionParentFolder(): Promise<string | undefined> { const workspaceFolders = vscode.workspace.workspaceFolders; const defaultFolder: vscode.Uri | undefined = workspaceFolders && workspaceFolders.length > 0 ? workspaceFolders[0].uri : undefined; const selectedUri: vscode.Uri[] | undefined = await vscode.window.showOpenDialog({ defaultUri: defaultFolder, openLabel: Constants.selectFolderLabel, canSelectFiles: false, canSelectFolders: true, canSelectMany: false, }); if (!selectedUri || selectedUri.length === 0) { return undefined; } return selectedUri[0].fsPath; } private async getDevKitTarball(): Promise<string | undefined> { const embeddedDevkitPath = this.getEmbeddedDevKitTarballPath(); const selectedUri: vscode.Uri[] | undefined = await vscode.window.showOpenDialog({ defaultUri: vscode.Uri.file(embeddedDevkitPath), openLabel: Constants.selectDevKitLabel, canSelectFiles: true, canSelectFolders: false, canSelectMany: false, filters: { "DevKit tarball": ["tar.gz"] }, }); if (!selectedUri || selectedUri.length === 0) { return undefined; } return selectedUri[0].fsPath; } private async inputSolutionName(parentPath: string, defaultName: string): Promise<string> { const validateFunc = async (name: string): Promise<string> => { return await this.validateSolutionName(name, parentPath) as string; }; return await Utility.showInputBox(Constants.solutionName, Constants.solutionNamePrompt, validateFunc, defaultName); } private async validateSolutionName(name: string, parentPath?: string): Promise<string | undefined> { if (!name || name.trim() === "") { return "The name could not be empty"; } if (!/^[0-9a-zA-Z_]+$/.test(name)) { return "Solution name must only contain characters: 0-9, a-z, A-Z, and _"; } if (parentPath) { const folderPath = path.join(parentPath, name); if (await fse.pathExists(folderPath)) { return `${name} already exists under ${parentPath}`; } } return undefined; } private async clearFolderAndThen(folder: string, resolve: any, reject: any, progress: ProgressUpdater, outputChannel: vscode.OutputChannel, callback: () => Promise<any>) { const clearFolderMessage = "Clearing folder: " + folder; this.progressAndOutput(clearFolderMessage, progress, outputChannel); fse.emptyDir( folder, (emptyDirErr) => { if (emptyDirErr) { // Empty failed, call reject this.progressAndOutput("Emptying folder failed.", progress, outputChannel); reject(emptyDirErr); } else { // Folder has been emptied, now remove it const removingFolderMessage = "Removing folder: " + folder; this.progressAndOutput(removingFolderMessage, progress, outputChannel); fse.rmdir( folder, (rmdirErr) => { if (rmdirErr) { this.progressAndOutput("Removing folder failed.", progress, outputChannel); reject(rmdirErr); } else { // Folder has been deleted, execute callback callback().then(() => { // Signal success resolve(); }).catch((callbackErr) => { // Signal callback failure reject(callbackErr); }); } }); } }); } private async promiseWithProgress(callback: (progress: ProgressUpdater, resolve: any, reject: any) => Promise<any>): Promise<void> { const progressOptions: IUserProgressOptions = userProgressOptionsDefaults; const options: IUserProgressOptions = { ...userProgressOptionsDefaults, ...progressOptions, }; return await vscode.window.withProgress( options as vscode.ProgressOptions, async (progress: ProgressUpdater) => { return new Promise<void>(async (resolve, reject) => { return await callback(progress, resolve, reject); }); }); } private progress(message: string, progress: ProgressUpdater) { this.progressAndOutput(message, progress, undefined); } private progressAndOutput(message: string, progress: ProgressUpdater, outputChannel: vscode.OutputChannel | undefined) { progress.report({ message }); if (outputChannel) { outputChannel.show(); outputChannel.appendLine(message); } } }
the_stack
import AOS from "aos"; import "aos/dist/aos.css"; import { useRef } from "react"; import { BsChevronCompactDown } from "react-icons/bs"; import { HiCheckCircle } from "react-icons/hi"; import { Link } from "react-router-dom"; import { PrismLight as SyntaxHighlighter } from "react-syntax-highlighter"; import jsonLang from "react-syntax-highlighter/dist/esm/languages/prism/json"; import solidityLang from "react-syntax-highlighter/dist/esm/languages/prism/solidity"; import lightStyle from "react-syntax-highlighter/dist/esm/styles/prism/ghcolors"; import codeStyle from "react-syntax-highlighter/dist/esm/styles/prism/vsc-dark-plus"; import ReactTooltip from "react-tooltip"; import arbitrum from "../../assets/chains/arbitrum.svg"; import avalanche from "../../assets/chains/avalanche.png"; import bsc from "../../assets/chains/binance.png"; import boba from "../../assets/chains/boba.png"; import celo from "../../assets/chains/celo.png"; import ethereum from "../../assets/chains/ethereum.png"; import optimism from "../../assets/chains/optimism.svg"; import polygon from "../../assets/chains/polygon.webp"; import xdai from "../../assets/chains/xdai.png"; import decode from "../../assets/decode.gif"; import openSourceDecentralized from "../../assets/openSourceDecentralized.svg"; import verification from "../../assets/verification.svg"; import Button from "../../components/Button"; import Header from "../../components/Header"; import { DOCS_URL, IPFS_IPNS_GATEWAY_URL, REPOSITORY_URL_FULL_MATCH, } from "../../constants"; import ChartSection from "./ChartSection"; import sourceCode from "./Contract.sol"; import CustomCarousel from "./CustomCarousel"; import metadata from "./metadata.json"; import PoweredBySourcify from "./PoweredBySourcify"; import ToolsPlugin from "./ToolsPlugin"; AOS.init({ duration: 800, once: true, }); SyntaxHighlighter.registerLanguage("solidity", solidityLang); SyntaxHighlighter.registerLanguage("json", jsonLang); // Helper components type ResourceListItemProps = { children: string; href: string; date?: string; }; const ResourceListItem = ({ children, href, date }: ResourceListItemProps) => ( <li> <a href={href} className="colored-bullet text-gray-600 hover:text-ceruleanBlue-500" > <span className="link-underline">{children}</span>{" "} {date && <span className="text-gray-400 text-sm">{"- " + date}</span>} </a> </li> ); type FooterItemProps = { href?: string; children: string; }; const FooterItem = ({ href, children }: FooterItemProps) => ( <a href={href}> <li className="text-ceruleanBlue-300 hover:text-ceruleanBlue-100"> {children} </li> </a> ); const A = ({ href, children }: FooterItemProps) => ( <a href={href} className="text-ceruleanBlue-500 link-underline"> {children} </a> ); ////////////////////////////////// ///////// MAIN COMPONENT ///////// ////////////////////////////////// const LandingPage = () => { const aboutRef = useRef<HTMLElement>(null); return ( <div> <div className="h-screen flex flex-col px-8 md:px-12 lg:px-24 bg-gray-100 "> <Header /> <section className="grid md:grid-cols-2 gap-8 flex-1"> {/* Hero left */} <div className="flex flex-col justify-center"> <h1 className="text-2xl md:text-3xl xl:text-4xl font-bold mb-4 leading-tight"> Source-verified smart contracts for transparency and better UX in web3 </h1> <h2 className="text-lg"> Sourcify enables transparent and human-readable smart contract interactions through automated Solidity contract verification, contract metadata, and NatSpec comments. </h2> <div className="flex flex-col items-center sm:flex-row justify-evenly mt-4"> <Link to="/verifier"> <Button>Verify Contract</Button> </Link> <Link to="/lookup"> <Button type="secondary">Lookup Contract</Button> </Link> </div> </div> {/* Hero right */} <div className="hidden md:flex items-center justify-center overflow-hidden" id="" > <div className="flex items-center justify-center relative w-full h-full" id="hero-image" > {/* Source code visual */} <div className="absolute mt-16 mr-16 xl:mt-32 xl:mr-32 z-10 transition-all duration-300 ease-in-out md:text-[0.6rem] lg:text-[0.7rem]" id="hero-source-code" > <SyntaxHighlighter language="solidity" style={codeStyle} className="rounded-md" customStyle={{ fontSize: "inherit", lineHeight: "1.2", padding: "1rem", }} wrapLongLines codeTagProps={{ style: { display: "block" } }} > {sourceCode} </SyntaxHighlighter> </div> {/* Verification visual */} <div className="absolute mb-16 ml-16 lg:ml-32 z-0 transition-all duration-300 ease-in-out bg-ceruleanBlue-100 px-4 py-2 rounded-md border-2 border-ceruleanBlue-400 text-xs lg:text-sm" id="hero-bytecode" > <div className="py-4"> <div className=" text-green-600 flex items-center"> <HiCheckCircle className="text-green-600 inline mr-1 align-middle text-xl" /> Contract fully verified </div> </div> <div className=""> <img src={ethereum} className="h-6 inline mb-1 -ml-1" alt="eth icon" /> <a href={`${REPOSITORY_URL_FULL_MATCH}/5/0x00878Ac0D6B8d981ae72BA7cDC967eA0Fae69df4`} className="link-underline break-all" > <b>Ethereum Görli</b> <br /> 0x00878Ac0D6B8d981ae72BA7cDC967eA0Fae69df4 </a> </div> <div className="mt-4 text-[0.6rem]"> <p className="text-sm">metadata.json</p> <SyntaxHighlighter language="json" style={lightStyle} className="rounded-md h-48 xl:h-64 p-3 m-3" customStyle={{ fontSize: "inherit", lineHeight: "1.2", }} wrapLongLines codeTagProps={{ style: { display: "block" } }} > {metadata} </SyntaxHighlighter> </div> </div> </div> </div> </section> <a className="my-4 flex justify-center" href="/#about"> <BsChevronCompactDown className="inline text-4xl animate-bounce text-gray-500" /> </a> </div> {/* About section */} <section className="px-8 md:px-12 lg:px-48 bg-white py-16" ref={aboutRef} id="about" > <div className="mt-12"> <div className="flex items-center flex-col md:flex-row"> <div className="flex-1" data-aos="fade-right"> <img src={openSourceDecentralized} alt="Illustration depicting open source and decentralized development" className="w-64 md:w-auto md:pr-48 md:pl-8 -scale-x-100" /> </div> <div className="flex-1 mt-4 md:mt-0" data-aos="fade-left"> <h1 className="text-2xl text-ceruleanBlue-500 font-bold"> Fully open-source and decentralized </h1>{" "} <p className="text-lg mt-4"> Sourcify's code is fully open-sourced. The repository of verified contracts is completely public and decentralized by being served over <A href={IPFS_IPNS_GATEWAY_URL}>IPFS</A>. </p> </div> </div> </div> <div className="my-24 md:text-right"> <div className="flex items-center flex-col-reverse md:flex-row"> <div className="flex-1 mt-4 md:mt-0" data-aos="fade-right"> <h1 className="text-2xl text-ceruleanBlue-500 font-bold"> Next-level smart contract verification </h1>{" "} <p className="text-lg mt-4"> <A href="https://docs.sourcify.dev/docs/full-vs-partial-match/"> Full matches </A>{" "} on Sourcify cryptographically guarantee the verified source code is identical to the original deployed contract. Our monitoring service observes contract creations and verifies the source codes automatically if published to IPFS. </p> </div> <div className="flex-1" data-aos="fade-left"> <img src={verification} alt="Illustration of contract verification" className="w-48 md:w-auto md:pr-48 md:pl-8 max-h-80" /> </div> </div> </div> <div className="mb-12" data-aos="fade-left"> <div className="flex items-center flex-col md:flex-row"> <div className="flex-1 flex md:justify-end mt-4 md:mt-0" data-aos="fade-right" > <img src={decode} alt="Decoding contract interaction with Sourcify" className="md:pl-48 md:pr-8" /> </div> <div className="flex-1 mt-4 md:mt-0" data-aos="fade-left"> <h1 className="text-2xl text-ceruleanBlue-500 font-bold"> Human-readable contract interactions </h1> <p className="text-lg"> Goodbye <i>YOLO signing</i> 👋. Decode contract interactions with the verified contract's ABI and{" "} <A href="https://docs.soliditylang.org/en/develop/natspec-format.html"> NatSpec comments </A>{" "} . Show wallet users meaningful information instead of hex strings. </p> </div> </div> </div> </section> {/* Supported Networks */} <section className="px-8 md:px-12 lg:px-24 bg-gray-100 py-16" data-aos="fade" > <h1 className="text-3xl text-ceruleanBlue-500 font-bold"> Supported Chains </h1> <div className="mt-8 text-lg"> <p>Sourcify is multi-chain and works on all EVM based networks.</p> </div> <ReactTooltip effect="solid" /> <div className="flex flex-row w-full justify-center py-16 logos-container flex-wrap"> <img src={ethereum} data-tip="Ethereum" className="h-12 md:h-24 transition-opacity mx-4 my-4 " alt="Ethereum logo" /> <img src={arbitrum} data-tip="Arbitrum" className="h-12 md:h-24 transition-opacity mx-4 my-4" alt="Arbitrum logo" /> <img src={avalanche} data-tip="Avalanche" className="h-12 md:h-24 transition-opacity mx-4 my-4" alt="Avalanche logo" /> <img src={bsc} data-tip="Binance Smart Chain" className="h-12 md:h-24 transition-opacity mx-4 my-4 rounded-full" alt="Binance Smart Chain logo" /> <img src={boba} data-tip="Boba Network" className="rounded-full h-12 md:h-24 transition-opacity mx-4 my-4" alt="Boba network logo" /> <img src={celo} data-tip="Celo" className="h-12 md:h-24 transition-opacity mx-4 my-4" alt="Celo logo" /> <img src={xdai} data-tip="Gnosis Chain (xDai)" className="h-12 md:h-24 transition-opacity mx-4 my-4 rounded-full" alt="Gnosis chain (xDai) logo" /> <img src={polygon} data-tip="Polygon" className="h-12 md:h-24 transition-opacity mx-4 my-4" alt="Polygon logo" /> <img src={optimism} data-tip="Optimism" className="h-12 md:h-24 transition-opacity mx-4 my-4" alt="Optimism logo" /> <div className="p-1 h-14 w-14 text-xs md:text-base md:h-24 md:w-24 transition-opacity rounded-full mx-4 my-4 text-ceruleanBlue-400 flex justify-center items-center text-center"> <a href={`${DOCS_URL}/docs/chains`}>And many more!</a> </div> </div> <div className="flex justify-center"> <a href={`${DOCS_URL}/docs/chains`} // className="underline decoration-lightCoral-500 decoration-2 font-semibold text-ceruleanBlue-500" className="link-underline font-semibold text-ceruleanBlue-500" > See all networks </a> </div> </section> {/* Integrations & Tools */} <section className="px-8 md:px-12 lg:px-24 bg-white py-16" data-aos="fade" > <h1 className="text-3xl text-ceruleanBlue-500 font-bold"> Integrations </h1> <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 mt-12 text-center md:text-left"> <div className="w-full"> <PoweredBySourcify /> <ToolsPlugin /> </div> <div className="flex mt-12"> <CustomCarousel /> </div> </div> <div className="mt-12"> <h3 className="text-center text-xl font-semibold text-ceruleanBlue-800"> Want to integrate Sourcify into your project? </h3> <div className="flex justify-center"> <a href={DOCS_URL}> <Button>Check Docs</Button> </a> <a href="https://gitter.im/ethereum/source-verify"> <Button type="secondary" className="ml-4"> Get in touch </Button> </a> </div> </div> </section> {/* Verified contract stats */} <section className="flex flex-col items-center px-8 md:px-12 lg:px-24 bg-gray-100 py-16" data-aos="fade" > <ChartSection /> </section> {/* Talks & Articles */} <section className="px-8 md:px-12 lg:px-24 bg-white py-16" data-aos="fade" > <h1 className="text-3xl text-ceruleanBlue-500 font-bold">Resources</h1> <div className="flex flex-col items-center mt-8"> <iframe className="sm:w-full sm:h-auto md:w-[48rem] md:h-[27rem]" src="https://www.youtube.com/embed/z5D613Qt7Kc" title="Next Level Source Code Verification w: Sourcify" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen ></iframe> <div className="grid grid-cols-1 md:grid-cols-2 gap-10 mt-8"> <ul> <h3 className="text-ceruleanBlue-500 uppercase text-lg font-semibold"> 📖 Read </h3> <ResourceListItem href="https://blog.soliditylang.org/2020/06/25/sourcify-faq/" date="25 Jun 2020" > All you need to know about Sourcify </ResourceListItem> <ResourceListItem href="https://blog.soliditylang.org/2020/06/02/Sourcify-Towards-Safer-Contract-Interaction-for-Humans/" date="02 June 2020" > Sourcify: Towards Safer Contract Interactions for Humans </ResourceListItem> <ResourceListItem href="https://news.shardlabs.io/how-smart-contracts-can-be-automatically-verified-28ee1c5cf941" date="29 Jan 2021" > How Smart Contracts Can Be Automatically Verified </ResourceListItem> <ResourceListItem href="https://medium.com/remix-ide/verify-contracts-on-remix-with-sourcify-2912004d9c84" date="26 Jun 2020" > Verify Contracts on Remix with Sourcify </ResourceListItem> <ResourceListItem href="https://soliditydeveloper.com/decentralized-etherscan/" date="21 Nov 2020" > The future of a Decentralized Etherscan </ResourceListItem> </ul> <ul> <h3 className="text-ceruleanBlue-500 uppercase text-lg font-semibold"> 📽 Watch </h3> <ResourceListItem href="https://vimeo.com/639594632" date="21 Oct 2021" > Goodbye YOLO-Signing </ResourceListItem> <ResourceListItem href="https://www.youtube.com/watch?v=Zc_fJElIooQ" date="22 Jul 2021" > Franziska Heintel : Sourcify: Towards Safer Contract Interactions for Humans </ResourceListItem> <ResourceListItem href="https://www.youtube.com/watch?v=uYvbBP3GEFk&list=PLaM7G4Llrb7xlGxwlYGTy1T-GHpytE3RC&index=23" date="13 May 2020" > Verify all the sources by Ligi </ResourceListItem> <ResourceListItem href="https://www.youtube.com/watch?v=_73OrDbpxoY&list=PLrtFm7U0BIfUH7g1-blb-eYFgzOYWhvqm&index=13" date="04 Mar 2020" > Christian Reitwiessner: Improving Wallet UX and Security through a Decentralized Metadata and Source Code Repository </ResourceListItem> </ul> </div> </div> </section> <footer className="text-center md:text-left px-8 py-8 md:px-48 md:py-16 bg-ceruleanBlue-500 text-white text-xl"> <nav className="font-vt323 grid md:grid-cols-3 gap-8"> <div> <h3 className="uppercase font-bold text-ceruleanBlue-100"> Internal Links </h3> <ul> <FooterItem href="/verifier">Contract Verifier</FooterItem> <FooterItem href="/lookup">Contract Lookup</FooterItem> {/* <FooterItem href="/status">Server Status</FooterItem> */} </ul> </div> <div> <h3 className="uppercase font-bold text-ceruleanBlue-100"> External Links </h3> <ul> <FooterItem href="https://docs.sourcify.dev"> Documentation </FooterItem> <FooterItem href={IPFS_IPNS_GATEWAY_URL}> Contract Repository (IPFS) </FooterItem> <FooterItem href="https://github.com/sourcifyeth/assets"> Brand Resources </FooterItem> </ul> </div> <div> <h3 className="uppercase font-bold text-ceruleanBlue-100"> Socials </h3> <ul> <FooterItem href="https://twitter.com/sourcifyeth"> Twitter </FooterItem> <FooterItem href="https://gitter.im/ethereum/source-verify"> Gitter </FooterItem> <FooterItem href="https://matrix.to/#/#ethereum_source-verify:gitter.im"> Matrix </FooterItem> <FooterItem href="https://github.com/ethereum/sourcify"> GitHub (main) </FooterItem> <FooterItem href="https://github.com/sourcifyeth"> GitHub (organization) </FooterItem> </ul> </div> </nav> <div className="text-center text-sm mt-8 text-ceruleanBlue-300"> Sourcify Team • {new Date().getFullYear()} • sourcify.eth{" "} </div> </footer> </div> ); }; export default LandingPage;
the_stack
// clang-format off import 'chrome://settings/lazy_load.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CrInputElement, PaymentsManagerImpl, SettingsCreditCardEditDialogElement, SettingsPaymentsSectionElement} from 'chrome://settings/lazy_load.js'; import {assertEquals, assertFalse, assertNotEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {eventToPromise, isVisible, whenAttributeIs} from 'chrome://webui-test/test_util.js'; import {createCreditCardEntry, TestPaymentsManager} from './passwords_and_autofill_fake_data.js'; // clang-format on /** * Helper function to simulate typing in nickname in the nickname field. */ function typeInNickname(nicknameInput: CrInputElement, nickname: string) { nicknameInput.value = nickname; nicknameInput.fire('input'); } suite('PaymentsSectionCreditCardEditDialogTest', function() { setup(function() { document.body.innerHTML = ''; }); /** * Creates the payments section for the given credit card list. */ function createPaymentsSection( creditCards: chrome.autofillPrivate.CreditCardEntry[]): SettingsPaymentsSectionElement { // Override the PaymentsManagerImpl for testing. const paymentsManager = new TestPaymentsManager(); paymentsManager.data.creditCards = creditCards; PaymentsManagerImpl.setInstance(paymentsManager); const section = document.createElement('settings-payments-section'); document.body.appendChild(section); flush(); return section; } /** * Creates the Add Credit Card dialog. Simulate clicking "Add" button in * payments section. */ function createAddCreditCardDialog(): SettingsCreditCardEditDialogElement { const section = createPaymentsSection(/*creditCards=*/[]); // Simulate clicking "Add" button in payments section. assertFalse(!!section.shadowRoot!.querySelector( 'settings-credit-card-edit-dialog')); section.$.addCreditCard.click(); flush(); const creditCardDialog = section.shadowRoot!.querySelector('settings-credit-card-edit-dialog'); assertTrue(!!creditCardDialog); return creditCardDialog!; } /** * Creates the Edit Credit Card dialog for existing local card by simulating * clicking three-dots menu button then clicking editing button of the first * card in the card list. */ function createEditCreditCardDialog( creditCards: chrome.autofillPrivate.CreditCardEntry[]): SettingsCreditCardEditDialogElement { const section = createPaymentsSection(creditCards); // Simulate clicking three-dots menu button for the first card in the list. const rowShadowRoot = section.$.paymentsList.shadowRoot! .querySelector('settings-credit-card-list-entry')!.shadowRoot!; assertFalse(!!rowShadowRoot.querySelector('#remoteCreditCardLink')); const menuButton = rowShadowRoot.querySelector<HTMLElement>('#creditCardMenu'); assertTrue(!!menuButton); menuButton!.click(); flush(); // Simulate clicking the 'Edit' button in the menu. section.$.menuEditCreditCard.click(); flush(); const creditCardDialog = section.shadowRoot!.querySelector('settings-credit-card-edit-dialog'); assertTrue(!!creditCardDialog); return creditCardDialog!; } function nextYear(): string { return (new Date().getFullYear() + 1).toString(); } function farFutureYear(): string { return (new Date().getFullYear() + 15).toString(); } function lastYear(): string { return (new Date().getFullYear() - 1).toString(); } test('add card dialog', async function() { const creditCardDialog = createAddCreditCardDialog(); // Wait for the dialog to open. await whenAttributeIs(creditCardDialog.$.dialog, 'open', ''); // Verify the nickname input field is shown when nickname management is // enabled. assertTrue(!!creditCardDialog.$.nicknameInput); assertTrue(!!creditCardDialog.$.nameInput); // Verify the card number field is autofocused when nickname management is // enabled. assertTrue(creditCardDialog.$.numberInput.matches(':focus-within')); }); test('save new card', async function() { const creditCardDialog = createAddCreditCardDialog(); // Wait for the dialog to open. await whenAttributeIs(creditCardDialog.$.dialog, 'open', ''); // Fill in name, card number, expiration year and card nickname, and trigger // the on-input handler. creditCardDialog.$.nameInput.value = 'Jane Doe'; creditCardDialog.$.numberInput.value = '4111111111111111'; typeInNickname(creditCardDialog.$.nicknameInput, 'Grocery Card'); creditCardDialog.$.year.value = nextYear(); creditCardDialog.$.year.dispatchEvent(new CustomEvent('change')); flush(); const expiredError = creditCardDialog.$.expiredError; assertEquals('hidden', getComputedStyle(expiredError).visibility); assertFalse(creditCardDialog.$.saveButton.disabled); const savedPromise = eventToPromise('save-credit-card', creditCardDialog); creditCardDialog.$.saveButton.click(); const saveEvent = await savedPromise; // Verify the input values are correctly passed to save-credit-card. // guid is undefined when saving a new card. assertEquals(saveEvent.detail.guid, undefined); assertEquals(saveEvent.detail.name, 'Jane Doe'); assertEquals(saveEvent.detail.cardNumber, '4111111111111111'); assertEquals(saveEvent.detail.nickname, 'Grocery Card'); assertEquals(saveEvent.detail.expirationYear, nextYear()); }); test('trim credit card when save', async function() { const creditCardDialog = createAddCreditCardDialog(); // Wait for the dialog to open. await whenAttributeIs(creditCardDialog.$.dialog, 'open', ''); // Set expiration year, fill in name, card number, and card nickname with // leading and trailing whitespaces, and trigger the on-input handler. creditCardDialog.$.nameInput.value = ' Jane Doe \n'; creditCardDialog.$.numberInput.value = ' 4111111111111111 '; typeInNickname(creditCardDialog.$.nicknameInput, ' Grocery Card '); creditCardDialog.$.year.value = nextYear(); creditCardDialog.$.year.dispatchEvent(new CustomEvent('change')); flush(); const expiredError = creditCardDialog.$.expiredError; assertEquals('hidden', getComputedStyle(expiredError).visibility); assertFalse(creditCardDialog.$.saveButton.disabled); const savedPromise = eventToPromise('save-credit-card', creditCardDialog); creditCardDialog.$.saveButton.click(); const saveEvent = await savedPromise; // Verify the input values are correctly passed to save-credit-card. // guid is undefined when saving a new card. assertEquals(saveEvent.detail.guid, undefined); assertEquals(saveEvent.detail.name, 'Jane Doe'); assertEquals(saveEvent.detail.cardNumber, '4111111111111111'); assertEquals(saveEvent.detail.nickname, 'Grocery Card'); assertEquals(saveEvent.detail.expirationYear, nextYear()); }); test('update local card value', async function() { const creditCard = createCreditCardEntry(); creditCard.name = 'Wrong name'; creditCard.nickname = 'Shopping Card'; // Set the expiration year to next year to avoid expired card. creditCard.expirationYear = nextYear(); creditCard.cardNumber = '4444333322221111'; const creditCardDialog = createEditCreditCardDialog([creditCard]); // Wait for the dialog to open. await whenAttributeIs(creditCardDialog.$.dialog, 'open', ''); // For editing local card, verify displaying with existing value. assertEquals(creditCardDialog.$.nameInput.value, 'Wrong name'); assertEquals(creditCardDialog.$.nicknameInput.value, 'Shopping Card'); assertEquals(creditCardDialog.$.numberInput.value, '4444333322221111'); assertEquals(creditCardDialog.$.year.value, nextYear()); const expiredError = creditCardDialog.$.expiredError; assertEquals('hidden', getComputedStyle(expiredError).visibility); assertFalse(creditCardDialog.$.saveButton.disabled); // Update cardholder name, card number, expiration year and nickname, and // trigger the on-input handler. creditCardDialog.$.nameInput.value = 'Jane Doe'; creditCardDialog.$.numberInput.value = '4111111111111111'; typeInNickname(creditCardDialog.$.nicknameInput, 'Grocery Card'); creditCardDialog.$.year.value = farFutureYear(); creditCardDialog.$.year.dispatchEvent(new CustomEvent('change')); flush(); const savedPromise = eventToPromise('save-credit-card', creditCardDialog); creditCardDialog.$.saveButton.click(); const saveEvent = await savedPromise; // Verify the updated values are correctly passed to save-credit-card. assertEquals(saveEvent.detail.guid, creditCard.guid); assertEquals(saveEvent.detail.name, 'Jane Doe'); assertEquals(saveEvent.detail.cardNumber, '4111111111111111'); assertEquals(saveEvent.detail.nickname, 'Grocery Card'); assertEquals(saveEvent.detail.expirationYear, farFutureYear()); }); test('show error message when input nickname is invalid', async function() { const creditCardDialog = createAddCreditCardDialog(); // Wait for the dialog to open. await whenAttributeIs(creditCardDialog.$.dialog, 'open', ''); // User clicks on nickname input. const nicknameInput = creditCardDialog.$.nicknameInput; assertTrue(!!nicknameInput); nicknameInput.focus(); const validInputs = [ '', ' ', '~@#$%^&**(){}|<>', 'Grocery Card', 'Two percent Cashback', /* UTF-16 hex encoded credit card emoji */ 'Chase Freedom \uD83D\uDCB3' ]; for (const nickname of validInputs) { typeInNickname(nicknameInput, nickname); assertFalse(nicknameInput.invalid); // Error message is hidden for valid nickname input. assertEquals( 'hidden', getComputedStyle(nicknameInput.$.error).visibility); } // Verify invalid nickname inputs. const invalidInputs = [ '12345', '2abc', 'abc3', 'abc4de', 'a 1 b', /* UTF-16 hex encoded digt 7 emoji */ 'Digit emoji: \u0037\uFE0F\u20E3' ]; for (const nickname of invalidInputs) { typeInNickname(nicknameInput, nickname); assertTrue(nicknameInput.invalid); assertNotEquals('', nicknameInput.errorMessage); // Error message is shown for invalid nickname input. assertEquals( 'visible', getComputedStyle(nicknameInput.$.error).visibility); } // The error message is still shown even when user does not focus on the // nickname field. nicknameInput.blur(); assertTrue(nicknameInput.invalid); assertEquals('visible', getComputedStyle(nicknameInput.$.error).visibility); }); test('disable save button when input nickname is invalid', async function() { const creditCard = createCreditCardEntry(); creditCard.name = 'Wrong name'; // Set the expiration year to next year to avoid expired card. creditCard.expirationYear = nextYear(); creditCard.cardNumber = '4444333322221111'; // Edit dialog for an existing card with no nickname. const creditCardDialog = createEditCreditCardDialog([creditCard]); // Wait for the dialog to open. await whenAttributeIs(creditCardDialog.$.dialog, 'open', ''); // Save button is enabled for existing card with no nickname. assertFalse(creditCardDialog.$.saveButton.disabled); const nicknameInput = creditCardDialog.$.nicknameInput; typeInNickname(nicknameInput, 'invalid: 123'); // Save button is disabled since the nickname is invalid. assertTrue(creditCardDialog.$.saveButton.disabled); typeInNickname(nicknameInput, 'valid nickname'); // Save button is back to enabled since user updates with a valid nickname. assertFalse(creditCardDialog.$.saveButton.disabled); }); test('only show nickname character count when focused', async function() { const creditCardDialog = createAddCreditCardDialog(); // Wait for the dialog to open. await whenAttributeIs(creditCardDialog.$.dialog, 'open', ''); const nicknameInput = creditCardDialog.$.nicknameInput; assertTrue(!!nicknameInput); const characterCount = creditCardDialog.shadowRoot!.querySelector<HTMLElement>('#charCount')!; // Character count is not shown when add card dialog is open (not focusing // on nickname input field). assertFalse(isVisible(characterCount)); // User clicks on nickname input. nicknameInput.focus(); // Character count is shown when nickname input field is focused. assertTrue(isVisible(characterCount)); // For new card, the nickname is unset. assertTrue(characterCount.textContent!.includes('0/25')); // User types in one character. Ensure the character count is dynamically // updated. typeInNickname(nicknameInput, 'a'); assertTrue(characterCount.textContent!.includes('1/25')); // User types in total 5 characters. typeInNickname(nicknameInput, 'abcde'); assertTrue(characterCount.textContent!.includes('5/25')); // User click outside of nickname input, the character count isn't shown. nicknameInput.blur(); assertFalse(isVisible(characterCount)); // User clicks on nickname input again. nicknameInput.focus(); // Character count is shown when nickname input field is re-focused. assertTrue(isVisible(characterCount)); assertTrue(characterCount.textContent!.includes('5/25')); }); test('expired card', async function() { const creditCard = createCreditCardEntry(); // Set the expiration year to the previous year to simulate expired card. creditCard.expirationYear = lastYear(); // Edit dialog for an existing card with no nickname. const creditCardDialog = createEditCreditCardDialog([creditCard]); // Wait for the dialog to open. await whenAttributeIs(creditCardDialog.$.dialog, 'open', ''); // Verify save button is disabled for expired credit card. assertTrue(creditCardDialog.$.saveButton.disabled); const expiredError = creditCardDialog.$.expiredError; // The expired error message is shown. assertEquals('visible', getComputedStyle(expiredError).visibility); // Check a11y attributes added for correct error announcement. assertEquals('alert', expiredError.getAttribute('role')); for (const select of [creditCardDialog.$.month, creditCardDialog.$.year]) { assertEquals('true', select.getAttribute('aria-invalid')); assertEquals(expiredError.id, select.getAttribute('aria-errormessage')); } // Update the expiration year to next year to avoid expired card. creditCardDialog.$.year.value = nextYear(); creditCardDialog.$.year.dispatchEvent(new CustomEvent('change')); flush(); // Expired error message is hidden for valid expiration date. assertEquals('hidden', getComputedStyle(expiredError).visibility); assertFalse(creditCardDialog.$.saveButton.disabled); // Check a11y attributes for expiration error removed. assertEquals(null, expiredError.getAttribute('role')); for (const select of [creditCardDialog.$.month, creditCardDialog.$.year]) { assertEquals('false', select.getAttribute('aria-invalid')); assertEquals(null, select.getAttribute('aria-errormessage')); } }); });
the_stack
import preact = require("preact"); const { h, Component } = preact; enum DefaultState { Closed, Open } interface GlobalConfig { defaultInstanceState: DefaultState rememberToggles: boolean } // Hackage domain-wide config const globalConfig: GlobalConfig = { defaultInstanceState: DefaultState.Open, rememberToggles: true, }; class PreferencesButton extends Component<any, any> { render(props: { title: string, onClick: () => void }) { function onClick(e: Event) { e.preventDefault(); props.onClick(); } return <li><a href="#" onClick={onClick}>{props.title}</a></li>; } } function addPreferencesButton(action: () => void) { const pageMenu = document.querySelector('#page-menu') as HTMLUListElement; const dummy = document.createElement('li'); pageMenu.insertBefore(dummy, pageMenu.firstChild); preact.render(<PreferencesButton onClick={action} title="Instances" />, pageMenu, dummy); } type PreferencesProps = { showHideTrigger: (action: () => void) => void } type PreferencesState = { isVisible: boolean } class Preferences extends Component<PreferencesProps, PreferencesState> { componentWillMount() { document.addEventListener('mousedown', this.hide.bind(this)); document.addEventListener('keydown', (e) => { if (this.state.isVisible) { if (e.key === 'Escape') { this.hide(); } } }) } hide() { this.setState({ isVisible: false }); } show() { if (!this.state.isVisible) { this.setState({ isVisible: true }); } } toggleVisibility() { if (this.state.isVisible) { this.hide(); } else { this.show(); } } componentDidMount() { this.props.showHideTrigger(this.toggleVisibility.bind(this)); } render(props: PreferencesProps, state: PreferencesState) { const stopPropagation = (e: Event) => { e.stopPropagation(); }; return <div id="preferences" class={state.isVisible ? '' : 'hidden'}> <div id="preferences-menu" class="dropdown-menu" onMouseDown={stopPropagation}> <PreferencesMenu /> </div> </div>; } } function storeGlobalConfig() { const json = JSON.stringify(globalConfig); try { // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions. localStorage.setItem('global', json); } catch (e) {} } var globalConfigLoaded: boolean = false; function loadGlobalConfig() { if (globalConfigLoaded) { return; } globalConfigLoaded = true; const global = localStorage.getItem('global'); if (!global) { return; } try { const globalConfig_ = JSON.parse(global); globalConfig.defaultInstanceState = globalConfig_.defaultInstanceState; globalConfig.rememberToggles = globalConfig_.rememberToggles; } catch(e) { // Gracefully handle errors related to changed config format. if (e instanceof SyntaxError || e instanceof TypeError) { localStorage.removeItem('global'); } else { throw e; } } } function setDefaultInstanceState(s: DefaultState) { return (e: Event) => { globalConfig.defaultInstanceState = s; putInstanceListsInDefaultState(); storeGlobalConfig(); clearLocalStorage(); storeLocalConfig(); } } function setRememberToggles(e: Event) { const checked: boolean = (e as any).target.checked; globalConfig.rememberToggles = checked; storeGlobalConfig(); clearLocalStorage(); storeLocalConfig(); } // Click event consumer for "default collapse" instance menu check box. function defaultCollapseOnClick(e: Event) { const us = document.getElementById('default-collapse-instances') as HTMLInputElement; if (us !== null) { if (us.checked) { setDefaultInstanceState(DefaultState.Closed)(e); } else { setDefaultInstanceState(DefaultState.Open)(e); } } } // Instances menu. function PreferencesMenu() { loadGlobalConfig(); return <div> <div> <button type="button" onClick={expandAllInstances}> Expand All Instances </button> <button type="button" onClick={collapseAllInstances}> Collapse All Instances </button> </div> <div> <input type="checkbox" id="default-collapse-instances" name="default-instance-state" checked={globalConfig.defaultInstanceState===DefaultState.Closed} onClick={defaultCollapseOnClick}></input> <span>Collapse All Instances By Default</span> </div> <div> <input type="checkbox" id="remember-toggles" name="remember-toggles" checked={globalConfig.rememberToggles} onClick={setRememberToggles}></input> <label for="remember-toggles">Remember Manually Collapsed/Expanded Instances</label> </div> </div>; } interface HTMLDetailsElement extends HTMLElement { open: boolean } interface DetailsInfo { element: HTMLDetailsElement // Here 'toggles' is the list of all elements of class // 'details-toggle-control' that control toggling 'element'. I // believe this list is always length zero or one. toggles: HTMLElement[] } // Mapping from <details> elements to their info. const detailsRegistry: { [id: string]: DetailsInfo } = {}; function lookupDetailsRegistry(id: string): DetailsInfo { const info = detailsRegistry[id]; if (info == undefined) { throw new Error(`could not find <details> element with id '${id}'`); } return info; } // Return true iff instance lists are open by default. function getDefaultOpenSetting(): boolean { return globalConfig.defaultInstanceState == DefaultState.Open; } // Event handler for "toggle" events, which are triggered when a // <details> element's "open" property changes. We don't deal with // any config stuff here, because we only change configs in response // to mouse clicks. In contrast, for example, this event is triggred // automatically once for every <details> element when the user clicks // the "collapse all elements" button. function onToggleEvent(ev: Event) { const element = ev.target as HTMLDetailsElement; const id = element.id; const info = lookupDetailsRegistry(id); const isOpen = info.element.open; // Update the CSS of the toggle element users can click on to toggle // 'element'. The "collapser" and "expander" classes control what // kind of arrow appears next to the 'toggle' element. for (const toggle of info.toggles) { if (toggle.classList.contains('details-toggle-control')) { toggle.classList.add(isOpen ? 'collapser' : 'expander'); toggle.classList.remove(isOpen ? 'expander' : 'collapser'); } } } function gatherDetailsElements() { const els: HTMLDetailsElement[] = Array.prototype.slice.call(document.getElementsByTagName('details')); for (const el of els) { if (typeof el.id == "string" && el.id.length > 0) { detailsRegistry[el.id] = { element: el, toggles: [] // Populated later by 'initCollapseToggles'. }; el.addEventListener('toggle', onToggleEvent); } } } // Return the id of the <details> element that the given 'toggle' // element toggles. function getDataDetailsId(toggle: Element): string { const id = toggle.getAttribute('data-details-id'); if (!id) { throw new Error("element with class " + toggle + " has no 'data-details-id' attribute!"); } return id; } // Toggle the "open" state of a <details> element when that element's // toggle element is clicked. function toggleDetails(toggle: Element) { const id = getDataDetailsId(toggle); const {element} = lookupDetailsRegistry(id); element.open = !element.open; } // Prefix for local keys used with local storage. Idea is that other // modules could also use local storage with a different prefix and we // wouldn't step on each other's toes. // // NOTE: we're using the browser's "local storage" API via the // 'localStorage' object to store both "local" (to the current Haddock // page) and "global" (across all Haddock pages) configuration. Be // aware of these two different uses of the term "local". const localStoragePrefix: string = "local-details-config:"; // Local storage key for the current page. function localStorageKey(): string { return localStoragePrefix + document.location.pathname; } // Clear all local storage related to instance list configs. function clearLocalStorage() { const keysToDelete: string[] = []; for (var i = 0; i < localStorage.length; ++i) { const key = localStorage.key(i); if (key !== null && key.startsWith(localStoragePrefix)) { keysToDelete.push(key); } } keysToDelete.forEach(key => { localStorage.removeItem(key); }); } // Compute and save the set of instance list ids that aren't in the // default state. function storeLocalConfig() { if (!globalConfig.rememberToggles) return; const instanceListToggles: HTMLElement[] = // Restrict to 'details-toggle' elements for "instances" // *plural*. These are the toggles that control instance lists and // not the list of methods for individual instances. Array.prototype.slice.call(document.getElementsByClassName( 'instances details-toggle details-toggle-control')); const nonDefaultInstanceListIds: string[] = []; instanceListToggles.forEach(toggle => { const id = getDataDetailsId(toggle); const details = document.getElementById(id) as HTMLDetailsElement; if (details.open != getDefaultOpenSetting()) { nonDefaultInstanceListIds.push(id); } }); const json = JSON.stringify(nonDefaultInstanceListIds); try { // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions. localStorage.setItem(localStorageKey(), json); } catch (e) {} } function putInstanceListsInDefaultState() { switch (globalConfig.defaultInstanceState) { case DefaultState.Closed: _collapseAllInstances(true); break; case DefaultState.Open: _collapseAllInstances(false); break; default: break; } } // Expand and collapse instance lists according to global and local // config. function restoreToggled() { loadGlobalConfig(); putInstanceListsInDefaultState(); if (!globalConfig.rememberToggles) { return; } const local = localStorage.getItem(localStorageKey()); if (!local) { return; } try { const nonDefaultInstanceListIds: string[] = JSON.parse(local); nonDefaultInstanceListIds.forEach(id => { const info = lookupDetailsRegistry(id); info.element.open = ! getDefaultOpenSetting(); }); } catch(e) { // Gracefully handle errors related to changed config format. if (e instanceof SyntaxError || e instanceof TypeError) { localStorage.removeItem(localStorageKey()); } else { throw e; } } } // Handler for clicking on the "toggle" element that toggles the // <details> element with id given by the 'data-details-id' property // of the "toggle" element. function onToggleClick(ev: MouseEvent) { ev.preventDefault(); const toggle = ev.currentTarget as HTMLElement; toggleDetails(toggle); storeLocalConfig(); } // Set event handlers on elements responsible for expanding and // collapsing <details> elements. // // This applies to all 'details-toggle's, not just to to top-level // 'details-toggle's that control instance lists. function initCollapseToggles() { const toggles: HTMLElement[] = Array.prototype.slice.call(document.getElementsByClassName('details-toggle')); toggles.forEach(toggle => { const id = getDataDetailsId(toggle); const info = lookupDetailsRegistry(id); info.toggles.push(toggle); toggle.addEventListener('click', onToggleClick); if (toggle.classList.contains('details-toggle-control')) { toggle.classList.add(info.element.open ? 'collapser' : 'expander'); } }); } // Collapse or expand all instances. function _collapseAllInstances(collapse: boolean) { const ilists = document.getElementsByClassName('subs instances'); [].forEach.call(ilists, function (ilist : Element) { const toggleType = collapse ? 'collapser' : 'expander'; const toggle = ilist.getElementsByClassName('instances ' + toggleType)[0]; if (toggle) { toggleDetails(toggle); } }); } function collapseAllInstances() { _collapseAllInstances(true); storeLocalConfig(); } function expandAllInstances() { _collapseAllInstances(false); storeLocalConfig(); } export function init(showHide?: (action: () => void) => void) { gatherDetailsElements(); initCollapseToggles(); restoreToggled(); preact.render( <Preferences showHideTrigger={showHide || addPreferencesButton} />, document.body ); }
the_stack
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { RequestService, DataCacheService, MessageService , AuthenticationService } from '../../core/services/index'; import { ToasterService} from 'angular2-toaster'; import 'rxjs/Rx'; import { Observable } from 'rxjs/Rx'; import { Subscription } from 'rxjs/Subscription'; // import { ServiceDetailComponent } from '../../service-detail/internal/service-detail.component' // import $ from 'jquery'; import { environment } from './../../../environments/environment'; import { environment as env_internal } from './../../../environments/environment.internal'; declare var $: any; @Component({ selector: 'service-overview-multienv', templateUrl: './service-overview-multienv.component.html', styleUrls: ['./service-overview-multienv.component.scss'] }) export class ServiceOverviewMultienvComponent implements OnInit { prodEnv: any = {}; stgEnv: any = {}; // Environments; @Output() onload: EventEmitter < any > = new EventEmitter < any > (); @Output() onEnvGet: EventEmitter < any > = new EventEmitter < any > (); flag: boolean = false; @Input() service: any = {}; @Input() isLoadingService: boolean = false; private subscription: any; list_env = [] list_inactive_env = []; copyLink: string = 'Copy Link'; disp_edit: boolean = true; hide_email_error: boolean = true; hide_slack_error: boolean = true; service_error: boolean = true; disp_show: boolean = false; err404: boolean = false; response_json: any; show_loader: boolean = false; plc_hldr: boolean = true; status_empty: boolean; description_empty: boolean; approvers_empty: boolean; domain_empty: boolean; serviceType_empty: boolean; email_empty: boolean; slackChannel_empty: boolean; repository_empty: boolean; runtime_empty: boolean = false; tags_empty: boolean; ErrEnv: boolean = false; accList = env_internal.urls.accounts; regList = env_internal.urls.regions; accSelected: string = this.accList[0]; regSelected: string = this.regList[0]; accounts = this.accList; regions = this.regList; errMessage = '' tags_temp: string = ''; desc_temp: string = ''; bitbucketRepo: string = ""; repositorylink: string = ""; islink: boolean = false; showCancel: boolean = false; private toastmessage: any = ''; // mod_status:string; private http: any; env_call:boolean = false; statusCompleted: boolean = false; serviceStatusCompleted: boolean = false; serviceStatusPermission: boolean = false; serviceStatusRepo: boolean = false; serviceStatusValidate: boolean = false; serviceStatusCompletedD: boolean = false; serviceStatusPermissionD: boolean = false; serviceStatusRepoD: boolean = false; serviceStatusValidateD: boolean = false; serviceStatusStarted: boolean = true; serviceStatusStartedD: boolean = false; statusFailed: boolean = false; statusInfo: string = 'Service Creation started'; private intervalSubscription: Subscription; swaggerUrl: string = ''; baseUrl: string = ''; service_request_id: any; creation_status: string; statusprogress: number = 20; noStg: boolean = false; noProd: boolean = false; DelstatusInfo: string = 'Deletion Started'; errBody: any; parsedErrBody: any; errorTime: any; errorURL: any; errorAPI: any; errorRequest: any = {}; errorResponse: any = {}; errorUser: any; envList = ['prod', 'stg']; friendlist = ['prod', 'stg']; errorChecked: boolean = true; errorInclude: any = ""; json: any = {}; errorcase: boolean = false; Nerrorcase: boolean = true; reqJson: any = {}; createloader: boolean = true; showbar: boolean = false; friendly_name: any; list: any = {}; constructor( private router: Router, private request: RequestService, private messageservice: MessageService, private cache: DataCacheService, private toasterService: ToasterService, // private serviceDetail:ServiceDetailComponent, private authenticationservice: AuthenticationService ) { this.http = request; this.toastmessage = messageservice; } email_temp: string; isenvLoading: boolean = false; token: string; noSubEnv: boolean = false; noEnv: boolean = false; slackChannel_temp: string; slackChannel_link: string = ''; edit_save: string = 'EDIT'; activeEnv: string = 'dev'; Environments = []; environ_arr = []; // prodEnv:any; // stgEnv:any; status: string = this.service.status; environments = [{ stageDisp: 'PROD', stage: 'prd', serviceHealth: 'NA', lastSuccess: {}, lastError: { value: 'NA', // unit: 'Days' }, deploymentsCount: { 'value': 'NA', 'duration': 'Last 24 hours' }, cost: { 'value': 'NA', 'duration': 'Per Day', // 'status': 'good' }, codeQuality: { 'value': 'NA', // 'status': 'bad' } }, { stageDisp: 'STAGE', stage: 'stg', serviceHealth: 'NA', lastSuccess: { value: 'NA', // unit: 'Days' }, lastError: {}, deploymentsCount: { 'value': 'NA', 'duration': 'Last 24 hours' }, cost: { 'value': 'NA', 'duration': 'Per Day', // 'status': 'good' }, codeQuality: { 'value': 'NA', // 'status': 'good' } } ]; branches = [{ title: 'DEV', stage: 'dev' }, { title: 'BRANCH1', stage: 'dev' }, { title: 'BRANCH2', stage: 'dev' }, { title: 'BRANCH3', stage: 'dev' }, { title: 'BRANCH4', stage: 'dev' }, // { // title:'BRANCH4', // stage:'dev' // }, // { // title:'BRANCH4', // stage:'dev' // }, // { // title:'BRANCH4', // stage:'dev' // } ]; stageClicked(stg) { let url = '/services/' + this.service['id'] + '/' + stg this.router.navigateByUrl(url); } toast_pop(error, oops, errorMessage) { var tst = document.getElementById('toast-container'); tst.classList.add('toaster-anim'); this.toasterService.pop(error, oops, errorMessage); setTimeout(() => { tst.classList.remove('toaster-anim'); }, 3000); } modifyEnvArr() { var j = 0; var k = 2; this.sortEnvArr(); if (this.environ_arr != undefined) { for (var i = 0; i < this.environ_arr.length; i++) { this.environ_arr[i].status = this.environ_arr[i].status.replace("_", " "); // this.environ_arr[i].status=this.environ_arr[i].status.split(" ").join("\ n") if (this.environ_arr[i].logical_id == 'prd' || this.environ_arr[i].logical_id == 'prod') { this.prodEnv = this.environ_arr[i]; continue; } if (this.environ_arr[i].logical_id == 'stg') { this.stgEnv = this.environ_arr[i]; continue; } else { if (this.environ_arr[i].status !== 'archived') { this.Environments[j] = this.environ_arr[i]; this.envList[k] = this.environ_arr[i].logical_id; if (this.environ_arr[i].friendly_name != undefined) { this.friendlist[k++] = this.environ_arr[i].friendly_name; } else { this.friendlist[k++] = this.environ_arr[i].logical_id; } j++; } } } this.list = { env: this.envList, friendly_name: this.friendlist } } if (this.Environments.length == 0) { this.noSubEnv = true; } if (this.prodEnv.logical_id == undefined) { this.noProd = true; } if (this.stgEnv.logical_id == undefined) { this.noStg = true; } // this.envList this.cache.set('envList', this.list); } sortEnvArr() { var j = 0; var k = 0; for (var i = 0; i < this.environ_arr.length; i++) { if (this.environ_arr[i].status != 'inactive') { this.list_env[j] = this.environ_arr[i]; // this.list_env[i] j++; } if (this.environ_arr[i].status == 'inactive') { this.list_inactive_env[k] = this.environ_arr[i]; k++; } } this.environ_arr = this.list_env.slice(0, this.list_env.length); this.environ_arr.push.apply(this.environ_arr, this.list_inactive_env); } getenvData() { this.isenvLoading = true; this.ErrEnv = false; if (this.service == undefined) { return } this.http.get('/jazz/environments?domain=' + this.service.domain + '&service=' + this.service.name, null, this.service.id).subscribe( response => { this.isenvLoading = false; this.environ_arr = response.data.environment; if (this.environ_arr != undefined) if (this.environ_arr.length == 0 || response.data == '') { this.noEnv = true; } this.ErrEnv = false; this.modifyEnvArr(); }, err => { this.isenvLoading = false; console.log('error', err); this.ErrEnv = true; if (err.status == 404) this.err404 = true; this.errMessage = "Something went wrong while fetching your data"; this.errMessage = this.toastmessage.errorMessage(err, "environment"); var payload = { "domain": +this.service.domain, "service": this.service.name } this.getTime(); this.errorURL = window.location.href; this.errorAPI = env_internal.baseurl + "/jazz/environments"; this.errorRequest = payload; this.errorUser = this.authenticationservice.getUserId(); this.errorResponse = JSON.parse(err._body); // let errorMessage=this.toastmessage.errorMessage(err,"serviceCost"); // this.popToast('error', 'Oops!', errorMessage); }) }; getTime() { var now = new Date(); this.errorTime = ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':' + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now.getSeconds()) : (now.getSeconds()))); // console.log(this.errorTime); } feedbackRes: boolean = false; openModal: boolean = false; feedbackMsg: string = ''; feedbackResSuccess: boolean = false; feedbackResErr: boolean = false; isFeedback: boolean = false; toast: any; model: any = { userFeedback: '' }; buttonText: string = 'SUBMIT'; isLoading: boolean = false; sjson: any = {}; djson: any = {}; is_multi_env: boolean = false; ngOnInit() { if (environment.multi_env) this.is_multi_env = true; if (environment.envName == 'oss') this.internal_build = false; var obj; this.prodEnv = {}; this.stgEnv = {}; if(!this.env_call){ if((this.service.domain!=undefined)){ this.env_call = true; this.getenvData(); } } } testingStatus() { setInterval(() => { this.onload.emit(this.service.status); }, 500); } transform_env_oss(data) { // alert('ososos') var arrEnv = data.data.environment if (environment.multi_env) { for (var i = 0; i < arrEnv.length; i++) { arrEnv[i].status = arrEnv[i].status.replace('_', ' '); if (arrEnv[i].logical_id == 'prod') this.prodEnv = arrEnv[i]; else this.Environments.push(arrEnv[i]); } } else { for (var i = 0; i < arrEnv.length; i++) { arrEnv[i].status = arrEnv[i].status.replace('_', ' '); if (arrEnv[i].logical_id == 'prod') this.prodEnv = arrEnv[i]; else this.stgEnv = arrEnv[i]; } } arrEnv[0].status.replace("_", " "); } refresh(){ if(this.service.domain!=undefined){ this.getenvData(); } } internal_build: boolean = true; ngOnChanges(x: any) { if (environment.multi_env) this.is_multi_env = true; if (environment.envName == 'oss') this.internal_build = false; var obj; if(!this.env_call){ if((this.service.domain!=undefined)){ this.env_call = true; this.getenvData(); } } } ngOnDestroy() { } public goToAbout(hash) { this.router.navigateByUrl('landing'); this.cache.set('scroll_flag', true); this.cache.set('scroll_id', hash); } scrollList: any; }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type MyBidsTestsQueryVariables = {}; export type MyBidsTestsQueryResponse = { readonly me: { readonly " $fragmentRefs": FragmentRefs<"MyBids_me">; } | null; }; export type MyBidsTestsQuery = { readonly response: MyBidsTestsQueryResponse; readonly variables: MyBidsTestsQueryVariables; }; /* query MyBidsTestsQuery { me { ...MyBids_me id } } fragment ActiveLotStanding_saleArtwork on SaleArtwork { ...Lot_saleArtwork isHighestBidder sale { status liveStartAt endAt id } lotState { bidCount reserveStatus soldStatus sellingPrice { display } } artwork { internalID href slug id } currentBid { display } estimate } fragment ClosedLotStanding_saleArtwork on SaleArtwork { ...Lot_saleArtwork isHighestBidder estimate artwork { internalID href slug id } lotState { soldStatus sellingPrice { display } } sale { endAt status id } } fragment LotStatusListItem_saleArtwork on SaleArtwork { ...ClosedLotStanding_saleArtwork ...ActiveLotStanding_saleArtwork ...WatchedLot_saleArtwork isWatching lotState { soldStatus } } fragment Lot_saleArtwork on SaleArtwork { lotLabel artwork { artistNames image { url(version: "medium") } id } } fragment MyBids_me on Me { ...SaleCard_me myBids { active { sale { ...SaleCard_sale internalID registrationStatus { qualifiedForBidding id } id } saleArtworks { ...LotStatusListItem_saleArtwork internalID id } } closed { sale { ...SaleCard_sale internalID registrationStatus { qualifiedForBidding id } id } saleArtworks { ...LotStatusListItem_saleArtwork internalID id } } } } fragment SaleCard_me on Me { identityVerified pendingIdentityVerification { internalID id } } fragment SaleCard_sale on Sale { internalID href slug name liveStartAt endAt coverImage { url } partner { name id } registrationStatus { qualifiedForBidding id } requireIdentityVerification } fragment WatchedLot_saleArtwork on SaleArtwork { ...Lot_saleArtwork lotState { bidCount sellingPrice { display } } artwork { internalID href slug id } currentBid { display } estimate } */ const node: ConcreteRequest = (function(){ var v0 = { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, v1 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "slug", "storageKey": null }, v4 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, v5 = { "alias": null, "args": null, "kind": "ScalarField", "name": "liveStartAt", "storageKey": null }, v6 = { "alias": null, "args": null, "kind": "ScalarField", "name": "endAt", "storageKey": null }, v7 = [ { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null } ], v8 = [ { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ (v0/*: any*/), (v2/*: any*/), (v3/*: any*/), (v4/*: any*/), (v5/*: any*/), (v6/*: any*/), { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "coverImage", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "url", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Partner", "kind": "LinkedField", "name": "partner", "plural": false, "selections": [ (v4/*: any*/), (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Bidder", "kind": "LinkedField", "name": "registrationStatus", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "qualifiedForBidding", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "requireIdentityVerification", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "saleArtworks", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "lotLabel", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "medium" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"medium\")" } ], "storageKey": null }, (v1/*: any*/), (v0/*: any*/), (v2/*: any*/), (v3/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isHighestBidder", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "estimate", "storageKey": null }, { "alias": null, "args": null, "concreteType": "CausalityLotState", "kind": "LinkedField", "name": "lotState", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "soldStatus", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Money", "kind": "LinkedField", "name": "sellingPrice", "plural": false, "selections": (v7/*: any*/), "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "bidCount", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "reserveStatus", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ (v6/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "status", "storageKey": null }, (v1/*: any*/), (v5/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtworkCurrentBid", "kind": "LinkedField", "name": "currentBid", "plural": false, "selections": (v7/*: any*/), "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isWatching", "storageKey": null }, (v0/*: any*/), (v1/*: any*/) ], "storageKey": null } ], v9 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, v10 = { "enumValues": null, "nullable": true, "plural": false, "type": "Boolean" }, v11 = { "enumValues": null, "nullable": true, "plural": true, "type": "MyBid" }, v12 = { "enumValues": null, "nullable": true, "plural": false, "type": "Sale" }, v13 = { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, v14 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }, v15 = { "enumValues": null, "nullable": true, "plural": false, "type": "Partner" }, v16 = { "enumValues": null, "nullable": true, "plural": false, "type": "Bidder" }, v17 = { "enumValues": null, "nullable": true, "plural": true, "type": "SaleArtwork" }, v18 = { "enumValues": null, "nullable": true, "plural": false, "type": "Artwork" }, v19 = { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtworkCurrentBid" }, v20 = { "enumValues": null, "nullable": true, "plural": false, "type": "CausalityLotState" }, v21 = { "enumValues": null, "nullable": true, "plural": false, "type": "Int" }, v22 = { "enumValues": null, "nullable": true, "plural": false, "type": "Money" }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "MyBidsTestsQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "MyBids_me" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "MyBidsTestsQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "identityVerified", "storageKey": null }, { "alias": null, "args": null, "concreteType": "IdentityVerification", "kind": "LinkedField", "name": "pendingIdentityVerification", "plural": false, "selections": [ (v0/*: any*/), (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "MyBids", "kind": "LinkedField", "name": "myBids", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "MyBid", "kind": "LinkedField", "name": "active", "plural": true, "selections": (v8/*: any*/), "storageKey": null }, { "alias": null, "args": null, "concreteType": "MyBid", "kind": "LinkedField", "name": "closed", "plural": true, "selections": (v8/*: any*/), "storageKey": null } ], "storageKey": null }, (v1/*: any*/) ], "storageKey": null } ] }, "params": { "id": "5cd0d822f0117f18f8e9f00724ab9a1a", "metadata": { "relayTestingSelectionTypeInfo": { "me": { "enumValues": null, "nullable": true, "plural": false, "type": "Me" }, "me.id": (v9/*: any*/), "me.identityVerified": (v10/*: any*/), "me.myBids": { "enumValues": null, "nullable": true, "plural": false, "type": "MyBids" }, "me.myBids.active": (v11/*: any*/), "me.myBids.active.sale": (v12/*: any*/), "me.myBids.active.sale.coverImage": (v13/*: any*/), "me.myBids.active.sale.coverImage.url": (v14/*: any*/), "me.myBids.active.sale.endAt": (v14/*: any*/), "me.myBids.active.sale.href": (v14/*: any*/), "me.myBids.active.sale.id": (v9/*: any*/), "me.myBids.active.sale.internalID": (v9/*: any*/), "me.myBids.active.sale.liveStartAt": (v14/*: any*/), "me.myBids.active.sale.name": (v14/*: any*/), "me.myBids.active.sale.partner": (v15/*: any*/), "me.myBids.active.sale.partner.id": (v9/*: any*/), "me.myBids.active.sale.partner.name": (v14/*: any*/), "me.myBids.active.sale.registrationStatus": (v16/*: any*/), "me.myBids.active.sale.registrationStatus.id": (v9/*: any*/), "me.myBids.active.sale.registrationStatus.qualifiedForBidding": (v10/*: any*/), "me.myBids.active.sale.requireIdentityVerification": (v10/*: any*/), "me.myBids.active.sale.slug": (v9/*: any*/), "me.myBids.active.saleArtworks": (v17/*: any*/), "me.myBids.active.saleArtworks.artwork": (v18/*: any*/), "me.myBids.active.saleArtworks.artwork.artistNames": (v14/*: any*/), "me.myBids.active.saleArtworks.artwork.href": (v14/*: any*/), "me.myBids.active.saleArtworks.artwork.id": (v9/*: any*/), "me.myBids.active.saleArtworks.artwork.image": (v13/*: any*/), "me.myBids.active.saleArtworks.artwork.image.url": (v14/*: any*/), "me.myBids.active.saleArtworks.artwork.internalID": (v9/*: any*/), "me.myBids.active.saleArtworks.artwork.slug": (v9/*: any*/), "me.myBids.active.saleArtworks.currentBid": (v19/*: any*/), "me.myBids.active.saleArtworks.currentBid.display": (v14/*: any*/), "me.myBids.active.saleArtworks.estimate": (v14/*: any*/), "me.myBids.active.saleArtworks.id": (v9/*: any*/), "me.myBids.active.saleArtworks.internalID": (v9/*: any*/), "me.myBids.active.saleArtworks.isHighestBidder": (v10/*: any*/), "me.myBids.active.saleArtworks.isWatching": (v10/*: any*/), "me.myBids.active.saleArtworks.lotLabel": (v14/*: any*/), "me.myBids.active.saleArtworks.lotState": (v20/*: any*/), "me.myBids.active.saleArtworks.lotState.bidCount": (v21/*: any*/), "me.myBids.active.saleArtworks.lotState.reserveStatus": (v14/*: any*/), "me.myBids.active.saleArtworks.lotState.sellingPrice": (v22/*: any*/), "me.myBids.active.saleArtworks.lotState.sellingPrice.display": (v14/*: any*/), "me.myBids.active.saleArtworks.lotState.soldStatus": (v14/*: any*/), "me.myBids.active.saleArtworks.sale": (v12/*: any*/), "me.myBids.active.saleArtworks.sale.endAt": (v14/*: any*/), "me.myBids.active.saleArtworks.sale.id": (v9/*: any*/), "me.myBids.active.saleArtworks.sale.liveStartAt": (v14/*: any*/), "me.myBids.active.saleArtworks.sale.status": (v14/*: any*/), "me.myBids.closed": (v11/*: any*/), "me.myBids.closed.sale": (v12/*: any*/), "me.myBids.closed.sale.coverImage": (v13/*: any*/), "me.myBids.closed.sale.coverImage.url": (v14/*: any*/), "me.myBids.closed.sale.endAt": (v14/*: any*/), "me.myBids.closed.sale.href": (v14/*: any*/), "me.myBids.closed.sale.id": (v9/*: any*/), "me.myBids.closed.sale.internalID": (v9/*: any*/), "me.myBids.closed.sale.liveStartAt": (v14/*: any*/), "me.myBids.closed.sale.name": (v14/*: any*/), "me.myBids.closed.sale.partner": (v15/*: any*/), "me.myBids.closed.sale.partner.id": (v9/*: any*/), "me.myBids.closed.sale.partner.name": (v14/*: any*/), "me.myBids.closed.sale.registrationStatus": (v16/*: any*/), "me.myBids.closed.sale.registrationStatus.id": (v9/*: any*/), "me.myBids.closed.sale.registrationStatus.qualifiedForBidding": (v10/*: any*/), "me.myBids.closed.sale.requireIdentityVerification": (v10/*: any*/), "me.myBids.closed.sale.slug": (v9/*: any*/), "me.myBids.closed.saleArtworks": (v17/*: any*/), "me.myBids.closed.saleArtworks.artwork": (v18/*: any*/), "me.myBids.closed.saleArtworks.artwork.artistNames": (v14/*: any*/), "me.myBids.closed.saleArtworks.artwork.href": (v14/*: any*/), "me.myBids.closed.saleArtworks.artwork.id": (v9/*: any*/), "me.myBids.closed.saleArtworks.artwork.image": (v13/*: any*/), "me.myBids.closed.saleArtworks.artwork.image.url": (v14/*: any*/), "me.myBids.closed.saleArtworks.artwork.internalID": (v9/*: any*/), "me.myBids.closed.saleArtworks.artwork.slug": (v9/*: any*/), "me.myBids.closed.saleArtworks.currentBid": (v19/*: any*/), "me.myBids.closed.saleArtworks.currentBid.display": (v14/*: any*/), "me.myBids.closed.saleArtworks.estimate": (v14/*: any*/), "me.myBids.closed.saleArtworks.id": (v9/*: any*/), "me.myBids.closed.saleArtworks.internalID": (v9/*: any*/), "me.myBids.closed.saleArtworks.isHighestBidder": (v10/*: any*/), "me.myBids.closed.saleArtworks.isWatching": (v10/*: any*/), "me.myBids.closed.saleArtworks.lotLabel": (v14/*: any*/), "me.myBids.closed.saleArtworks.lotState": (v20/*: any*/), "me.myBids.closed.saleArtworks.lotState.bidCount": (v21/*: any*/), "me.myBids.closed.saleArtworks.lotState.reserveStatus": (v14/*: any*/), "me.myBids.closed.saleArtworks.lotState.sellingPrice": (v22/*: any*/), "me.myBids.closed.saleArtworks.lotState.sellingPrice.display": (v14/*: any*/), "me.myBids.closed.saleArtworks.lotState.soldStatus": (v14/*: any*/), "me.myBids.closed.saleArtworks.sale": (v12/*: any*/), "me.myBids.closed.saleArtworks.sale.endAt": (v14/*: any*/), "me.myBids.closed.saleArtworks.sale.id": (v9/*: any*/), "me.myBids.closed.saleArtworks.sale.liveStartAt": (v14/*: any*/), "me.myBids.closed.saleArtworks.sale.status": (v14/*: any*/), "me.pendingIdentityVerification": { "enumValues": null, "nullable": true, "plural": false, "type": "IdentityVerification" }, "me.pendingIdentityVerification.id": (v9/*: any*/), "me.pendingIdentityVerification.internalID": (v9/*: any*/) } }, "name": "MyBidsTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = 'b171cc29f771a471afbf0365e3b1cc5e'; export default node;
the_stack
import { BrowserWindow, clipboard, Menu, MenuItem, MenuItemConstructorOptions, shell } from 'electron'; import { ElectronWindow, promptYesNoSync, selectInput } from '../../common'; import { App } from '../app'; import { PopoutHandler } from '../popoutHandler/popoutHandler'; import { settings } from '../settingHandler'; import { ThemeHandler } from '../themeHandler/themeHandler'; function appMenuSetup(mainApp: App, themeHandler: ThemeHandler, popoutHandler: PopoutHandler): Menu { const template: MenuItemConstructorOptions[] = [ { label: 'App', submenu: [ { label: 'Themes', submenu: [ { label: 'Choose Theme', click() { themeHandler.openWindow(); } }, { label: 'Make Theme', click() { themeHandler.openMaker(); } } ] }, { label: 'Links', submenu: [ { label: 'CLI', click(i: MenuItem, win: BrowserWindow) { win.loadURL('https://replit.com/~/cli').catch(); } }, { label: 'Replit Feedback', click(i: MenuItem, win: BrowserWindow) { win.loadURL('https://replit.canny.io').catch(); } }, { label: 'Docs', click() { let win = new ElectronWindow( { height: 900, width: 1600 }, '', true ); win.loadURL('https://docs.replit.com'); } } ] }, { label: 'Discord', submenu: [ { label: 'Reconnect to Discord', click() { mainApp.discordHandler.connectDiscord(); } }, { label: 'Disconnect from Discord', click() { mainApp.discordHandler.disconnectDiscord(); } } ] }, { type: 'separator' }, { label: 'Restore Session', type: 'checkbox', checked: <boolean>settings.has('restore-url'), click(item: MenuItem, win: BrowserWindow) { mainApp.toggleRestoreSession(item, <ElectronWindow>win); } }, { label: 'Clear Cookies', click() { mainApp.clearCookies(false, false, true); } }, { label: 'Reset Settings', click() { mainApp.resetPreferences(); } }, { type: 'separator' }, { role: 'quit' } ] }, { label: 'View', submenu: [ { label: 'Popout Terminal', click(i: MenuItem, win: BrowserWindow) { popoutHandler.launch(<ElectronWindow>win); } }, { label: 'Mobile View', type: 'checkbox', checked: <boolean>settings.get('enable-ace'), click(item: MenuItem) { mainApp.toggleAce(item); } }, { label: 'Crosis Logs', click(i: MenuItem, win: ElectronWindow) { // suggestion: check if the page is on a repl, and if so, just add ?debug=1 win.webContents.executeJavaScript( "if(!window.store){alert('You need to be on a repl to use this feature.')};window.store.dispatch({type: 'LOAD_PLUGIN',pluginPud: 'adminpanel',pluginType: 'adminpanel',title: 'adminpanel'});window.store.dispatch({type: 'ADD_SIDE_NAV_ITEM',navItem: {pud: 'adminpanel',pluginType: 'adminpanel',tooltip: 'Crosis Logs',svg: 'Alien'}});" ); } } ] }, { label: 'Edit', submenu: [ { role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'pasteAndMatchStyle' }, { role: 'delete' }, { role: 'selectAll' }, { type: 'separator' }, { label: 'Copy URL to clipboard', click(i: MenuItem, win: BrowserWindow) { clipboard.writeText(win.webContents.getURL()); } } ] }, { label: 'Window', submenu: [ { label: 'Go Back', click: (i: MenuItem, win: BrowserWindow) => { if (win.webContents.canGoBack()) { win.webContents.goBack(); } } }, { label: 'Go Forward', click: (i: MenuItem, win: BrowserWindow) => { if (win.webContents.canGoForward()) { win.webContents.goForward(); } } }, { type: 'separator' }, { label: 'Open in Browser', click: (i: MenuItem, win: BrowserWindow) => { shell.openExternal(win.webContents.getURL()); } }, { label: 'Go to Home', click: (i: MenuItem, win: BrowserWindow) => { win.loadURL('https://replit.com/~').catch(); } }, /* { accelerator: 'CmdOrCtrl+f', label: 'Select input', click(i: MenuItem, win: BrowserWindow) { selectInput(<ElectronWindow>win); } },*/ { type: 'separator' }, { accelerator: 'CmdOrCtrl+R', label: 'Reload', click: (i: MenuItem, win: BrowserWindow) => { if (win) win.reload(); } }, { label: 'Toggle Developer Tools', accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I', click: (i: MenuItem, win: BrowserWindow) => { if (win) win.webContents.toggleDevTools(); } }, { type: 'separator' }, { role: 'resetZoom' }, { role: 'zoomIn' }, { role: 'zoomOut' }, { type: 'separator' }, { role: 'togglefullscreen' }, { role: 'minimize' }, { role: 'close' } ] }, { role: 'help', submenu: [ { label: 'Replit discord', click() { shell.openExternal('https://replit.com/discord'); } }, { label: 'Report an issue', click() { shell.openExternal('https://github.com/repl-it-discord/repl-it-electron/issues/new/choose'); } }, { label: 'Github Repo', click() { shell.openExternal('https://github.com/repl-it-discord/repl-it-electron'); } }, { label: 'Version', role: 'about' } ] } ]; return Menu.buildFromTemplate(template); } export { appMenuSetup };
the_stack
import { Dialog, showDialog, showErrorMessage } from '@jupyterlab/apputils'; import { TranslationBundle } from '@jupyterlab/translation'; import { CommandRegistry } from '@lumino/commands'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ClearIcon from '@material-ui/icons/Clear'; import * as React from 'react'; import { FixedSizeList, ListChildComponentProps } from 'react-window'; import { classes } from 'typestyle'; import { Logger } from '../logger'; import { hiddenButtonStyle } from '../style/ActionButtonStyle'; import { activeListItemClass, nameClass, filterClass, filterClearClass, filterInputClass, filterWrapperClass, listItemClass, listItemIconClass, newBranchButtonClass, wrapperClass } from '../style/BranchMenu'; import { branchIcon, mergeIcon, trashIcon } from '../style/icons'; import { CommandIDs, Git, IGitExtension, Level } from '../tokens'; import { ActionButton } from './ActionButton'; import { NewBranchDialog } from './NewBranchDialog'; const ITEM_HEIGHT = 24.8; // HTML element height for a single branch const MIN_HEIGHT = 150; // Minimal HTML element height for the branches list const MAX_HEIGHT = 400; // Maximal HTML element height for the branches list /** * Callback invoked upon encountering an error when switching branches. * * @private * @param error - error * @param logger - the logger */ function onBranchError( error: any, logger: Logger, trans: TranslationBundle ): void { if (error.message.includes('following files would be overwritten')) { // Empty log message to hide the executing alert logger.log({ message: '', level: Level.INFO }); showDialog({ title: trans.__('Unable to switch branch'), body: ( <React.Fragment> <p> {trans.__( 'Your changes to the following files would be overwritten by switching:' )} </p> <List> {error.message.split('\n').slice(1, -3).map(renderFileName)} </List> <span> {trans.__( 'Please commit, stash, or discard your changes before you switch branches.' )} </span> </React.Fragment> ), buttons: [Dialog.okButton({ label: trans.__('Dismiss') })] }); } else { logger.log({ level: Level.ERROR, message: trans.__('Failed to switch branch.'), error }); } } /** * Renders a file name. * * @private * @param filename - file name * @returns React element */ function renderFileName(filename: string): React.ReactElement { return <ListItem key={filename}>{filename}</ListItem>; } /** * Interface describing component properties. */ export interface IBranchMenuProps { /** * Current branch name. */ currentBranch: string; /** * Current list of branches. */ branches: Git.IBranch[]; /** * Boolean indicating whether branching is disabled. */ branching: boolean; /** * Jupyter App commands registry */ commands: CommandRegistry; /** * Extension logger */ logger: Logger; /** * Git extension data model. */ model: IGitExtension; /** * The application language translator. */ trans: TranslationBundle; } /** * Interface describing component state. */ export interface IBranchMenuState { /** * Boolean indicating whether to show a dialog to create a new branch. */ branchDialog: boolean; /** * Menu filter. */ filter: string; } /** * React component for rendering a branch menu. */ export class BranchMenu extends React.Component< IBranchMenuProps, IBranchMenuState > { CHANGES_ERR_MSG = this.props.trans.__( 'The current branch contains files with uncommitted changes. Please commit or discard these changes before switching to or creating another branch.' ); /** * Returns a React component for rendering a branch menu. * * @param props - component properties * @returns React component */ constructor(props: IBranchMenuProps) { super(props); this.state = { filter: '', branchDialog: false }; } /** * Renders the component. * * @returns React element */ render(): React.ReactElement { return ( <div className={wrapperClass}> {this._renderFilter()} {this._renderBranchList()} {this._renderNewBranchDialog()} </div> ); } /** * Renders a branch input filter. * * @returns React element */ private _renderFilter(): React.ReactElement { return ( <div className={filterWrapperClass}> <div className={filterClass}> <input className={filterInputClass} type="text" onChange={this._onFilterChange} value={this.state.filter} placeholder={this.props.trans.__('Filter')} title={this.props.trans.__('Filter branch menu')} /> {this.state.filter ? ( <button className={filterClearClass}> <ClearIcon titleAccess={this.props.trans.__('Clear the current filter')} fontSize="small" onClick={this._resetFilter} /> </button> ) : null} </div> <input className={newBranchButtonClass} type="button" title={this.props.trans.__('Create a new branch')} value={this.props.trans.__('New Branch')} onClick={this._onNewBranchClick} /> </div> ); } /** * Renders a * * @returns React element */ private _renderBranchList(): React.ReactElement { // Perform a "simple" filter... (TODO: consider implementing fuzzy filtering) const filter = this.state.filter; const branches = this.props.branches.filter( branch => !filter || branch.name.includes(filter) ); return ( <FixedSizeList height={Math.min( Math.max(MIN_HEIGHT, branches.length * ITEM_HEIGHT), MAX_HEIGHT )} itemCount={branches.length} itemData={branches} itemKey={(index, data) => data[index].name} itemSize={ITEM_HEIGHT} style={{ overflowX: 'hidden', paddingTop: 0, paddingBottom: 0 }} width={'auto'} > {this._renderItem} </FixedSizeList> ); } /** * Renders a menu item. * * @param props Row properties * @returns React element */ private _renderItem = (props: ListChildComponentProps): JSX.Element => { const { data, index, style } = props; const branch = data[index] as Git.IBranch; const isActive = branch.name === this.props.currentBranch; return ( <ListItem button title={ !isActive ? this.props.trans.__('Switch to branch: %1', branch.name) : '' } className={classes( listItemClass, isActive ? activeListItemClass : null )} onClick={this._onBranchClickFactory(branch.name)} style={style} > <branchIcon.react className={listItemIconClass} tag="span" /> <span className={nameClass}>{branch.name}</span> {!branch.is_remote_branch && !isActive && ( <> <ActionButton className={hiddenButtonStyle} icon={trashIcon} title={this.props.trans.__('Delete this branch locally')} onClick={(event: React.MouseEvent) => { event.stopPropagation(); this._onDeleteBranch(branch.name); }} /> <ActionButton className={hiddenButtonStyle} icon={mergeIcon} title={this.props.trans.__( 'Merge this branch into the current one' )} onClick={(event: React.MouseEvent) => { event.stopPropagation(); this._onMergeBranch(branch.name); }} /> </> )} </ListItem> ); }; /** * Renders a dialog for creating a new branch. * * @returns React element */ private _renderNewBranchDialog(): React.ReactElement { return ( <NewBranchDialog currentBranch={this.props.currentBranch} branches={this.props.branches} logger={this.props.logger} open={this.state.branchDialog} model={this.props.model} onClose={this._onNewBranchDialogClose} trans={this.props.trans} /> ); } /** * Callback invoked upon a change to the menu filter. * * @param event - event object */ private _onFilterChange = (event: any): void => { this.setState({ filter: event.target.value }); }; /** * Callback invoked to reset the menu filter. */ private _resetFilter = (): void => { this.setState({ filter: '' }); }; /** * Callback on delete branch name button * * @param branchName Branch name */ private _onDeleteBranch = async (branchName: string): Promise<void> => { const acknowledgement = await showDialog<void>({ title: this.props.trans.__('Delete branch'), body: ( <p> {this.props.trans.__( 'Are you sure you want to permanently delete the branch ' )} <b>{branchName}</b>? <br /> {this.props.trans.__('This action cannot be undone.')} </p> ), buttons: [ Dialog.cancelButton({ label: this.props.trans.__('Cancel') }), Dialog.warnButton({ label: this.props.trans.__('Delete') }) ] }); if (acknowledgement.button.accept) { try { await this.props.model.deleteBranch(branchName); await this.props.model.refreshBranch(); } catch (error) { console.error(`Failed to delete branch ${branchName}`, error); } } }; /** * Callback on merge branch name button * * @param branchName Branch name */ private _onMergeBranch = async (branch: string): Promise<void> => { await this.props.commands.execute(CommandIDs.gitMerge, { branch }); }; /** * Callback invoked upon clicking a button to create a new branch. * * @param event - event object */ private _onNewBranchClick = (): void => { if (!this.props.branching) { showErrorMessage( this.props.trans.__('Creating a new branch is disabled'), this.CHANGES_ERR_MSG ); return; } this.setState({ branchDialog: true }); }; /** * Callback invoked upon closing a dialog to create a new branch. */ private _onNewBranchDialogClose = (): void => { this.setState({ branchDialog: false }); }; /** * Returns a callback which is invoked upon clicking a branch name. * * @param branch - branch name * @returns callback */ private _onBranchClickFactory(branch: string) { const self = this; return onClick; /** * Callback invoked upon clicking a branch name. * * @private * @param event - event object * @returns promise which resolves upon attempting to switch branches */ async function onClick(): Promise<void> { if (!self.props.branching) { showErrorMessage( self.props.trans.__('Switching branches is disabled'), self.CHANGES_ERR_MSG ); return; } const opts = { branchname: branch }; self.props.logger.log({ level: Level.RUNNING, message: self.props.trans.__('Switching branch…') }); try { await self.props.model.checkout(opts); } catch (err) { return onBranchError(err, self.props.logger, self.props.trans); } self.props.logger.log({ level: Level.SUCCESS, message: self.props.trans.__('Switched branch.') }); } } }
the_stack
import { CanvasInstruction } from "../../src/shared/CanvasInstruction"; import { Buffer } from "../internal/Buffer"; import { DOMMatrix } from "./DOMMatrix"; import { CanvasDirection } from "../../src/shared/CanvasDirection"; import { CanvasPattern } from "./CanvasPattern"; import { CanvasGradient } from "./CanvasGradient"; import { Image, getImageID } from "./Image"; import { CanvasPatternRepetition } from "../../src/shared/CanvasPatternRepetition"; import { GlobalCompositeOperation } from "../../src/shared/GlobalCompositeOperation"; import { ImageSmoothingQuality } from "../../src/shared/ImageSmoothingQuality"; import { LineCap } from "../../src/shared/LineCap"; import { LineJoin } from "../../src/shared/LineJoin"; import { TextAlign } from "../../src/shared/TextAlign"; import { TextBaseline } from "../../src/shared/TextBaseline"; import { arraysEqual } from "../internal/util"; import { Path2DElement } from "../internal/Path2DElement"; import { FillRule } from "../../src/shared/FillRule"; import { STORE, LOAD } from "../internal/util"; import { StackPointer } from "../internal/StackPointer"; import { CanvasStack } from "./CanvasStack"; import { FillStrokeStyleType } from "../internal/FillStrokeStyleType"; // @ts-ignore: linked functions can have decorators @external("__canvas_sys", "render") declare function render(ctxid: i32, data: usize): void; // @ts-ignore: linked functions can have decorators @external("__canvas_sys", "createLinearGradient") declare function createLinearGradient(id: i32, x0: f64, y0: f64, x1: f64, y1: f64): i32; // @ts-ignore: linked functions can have decorators @external("__canvas_sys", "createRadialGradient") declare function createRadialGradient(id: i32, x0: f64, y0: f64, r0: f64, x1: f64, y1: f64, r1: f64): i32; // @ts-ignore: linked functions can have decorators @external("__canvas_sys", "createPattern") declare function createPattern(ctxid: i32, imageid: i32, repetition: CanvasPatternRepetition): i32; // @ts-ignore: linked functions can have decorators @external("__canvas_sys", "measureText") declare function measureText(id: i32, text: string): f64; // @ts-ignore: linked functions can have decorators @external("__canvas_sys", "isPointInPath") declare function isPointInPath(id: i32, x: f64, y: f64, fillRule: FillRule): bool; // @ts-ignore: linked functions can have decorators @external("__canvas_sys", "isPointInStroke") declare function isPointInStroke(id: i32, x: f64, y: f64): bool; var defaultBlack: string = "#000"; var defaultNone: string = "none"; var defaultFont: string = "10px sans-serif"; var defaultShadowColor: string = "rgba(0, 0, 0, 0)"; var defaultLineDash: Float64Array = new Float64Array(0); //#region ARRAYBUFFERINITIALIZER /** * Utility function for setting the given ArrayBuffer to the identity 2d transform matrix inline. * * @param ArrayBuffer buff */ // @ts-ignore: Decorators are valid here function setArrayBufferIdentity(buff: usize): usize { STORE<f64>(buff, 0, 1.0); STORE<f64>(buff, 1, 0.0); STORE<f64>(buff, 2, 0.0); STORE<f64>(buff, 3, 1.0); STORE<f64>(buff, 4, 0.0); STORE<f64>(buff, 5, 0.0); return buff; } function initializeStackPointer(pointer: StackPointer<CanvasStack>): StackPointer<CanvasStack> { let stack = pointer.reference(); stack.a = 1; stack.d = 1; stack.direction = CanvasDirection.inherit; stack.fillStyleType = FillStrokeStyleType.String; stack.fillStyleString = defaultBlack; __retain(changetype<usize>(defaultBlack)); stack.filter = defaultNone; __retain(changetype<usize>(defaultNone)); stack.font = defaultFont; __retain(changetype<usize>(defaultFont)); stack.globalAlpha = 1.0; stack.globalCompositeOperation = GlobalCompositeOperation.source_over; stack.imageSmoothingEnabled = true; stack.imageSmoothingQuality = ImageSmoothingQuality.low; stack.lineCap = LineCap.butt; stack.lineDash = defaultLineDash; stack.lineJoin = LineJoin.miter; stack.lineWidth = 1.0; stack.miterLimit = 10.0; stack.shadowBlur = 0.0; stack.shadowColor = defaultShadowColor; stack.strokeStyleString = defaultBlack; __retain(changetype<usize>(defaultBlack)); __retain(changetype<usize>(defaultShadowColor)); return pointer; } /** The path element initializer. */ function createPathElements(): StackPointer<Path2DElement> { let pointer = StackPointer.create<Path2DElement>(0x1000); let reference = pointer.reference(); reference.instruction = CanvasInstruction.BeginPath; reference.count = 0; reference.updateTransform = true; reference.transformA = 1.0; reference.transformD = 1.0; return pointer; } /** * An AssemblyScript virtual representation of an actual CanvasRenderingContext2D Object. The * CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context * for the drawing surface of a <canvas> element. It is used for drawing shapes, text, images, and * other objects. */ @sealed export class CanvasRenderingContext2D extends Buffer<CanvasInstruction> { /** * The component's external object id. It initializes to -1, which will never be an actual object * id externally. If it actually returns -1, it will cause the host to error saying it cannot * find the specified canvas context. */ private id: i32 = -1; /** * The virutal stack index offset that keeps track of the number of `save()` and `restore()` * stack states. */ private _stackOffset: u8 = <u8>0; //#region CREATELINEARGRADIENT /** * The CanvasRenderingContext2D.createLinearGradient() method of the Canvas 2D API creates a * gradient along the line connecting two given coordinates. * * @param {f64} x0 - A float number representing the first x coordinate point of the gradient. * @param {f64} y0 - A float number representing the first y coordinate point of the gradient. * @param {f64} x1 - A float number representing the second x coordinate point of the gradient. * @param {f64} y1 - A float number representing the second y coordinate point of the gradient. */ public createLinearGradient(x0: f64, y0: f64, x1: f64, y1: f64): CanvasGradient { var id: i32 = createLinearGradient(this.id, x0, y0, x1, y1); var result: CanvasGradient = new CanvasGradient(); store<i32>(changetype<usize>(result), id, offsetof<CanvasGradient>("id")); return result; } //#endregion CREATELINEARGRADIENT //#region CREATERADIALGRADIENT /** * The CanvasRenderingContext2D.createRadialGradient() method of the Canvas 2D API creates a * radial gradient using the size and coordinates of two circles. * * @param {f64} x0 - The x-axis coordinate of the start circle. * @param {f64} y0 - The y-axis coordinate of the start circle. * @param {f64} r0 - The radius of the start circle. Must be non-negative and finite. * @param {f64} x1 - The x-axis coordinate of the end circle. * @param {f64} y1 - The y-axis coordinate of the end circle. * @param {f64} r1 - The radius of the end circle. Must be non-negative and finite. */ public createRadialGradient(x0: f64, y0: f64, r0: f64, x1: f64, y1: f64, r1: f64): CanvasGradient { var id: i32 = createRadialGradient(this.id, x0, y0, r0, x1, y1, r1); var result: CanvasGradient = new CanvasGradient(); store<i32>(changetype<usize>(result), id, offsetof<CanvasGradient>("id")); return result; } //#endregion CREATERADIALGRADIENT private _stack: StackPointer<CanvasStack> = initializeStackPointer(StackPointer.create<CanvasStack>(0xFF)); //#region TRANSFORM /** * An ArrayBuffer that contains a single transform value that represents the last transform * written by a `setTransform()` operation */ private _currentTransform: ArrayBuffer = changetype<ArrayBuffer>(setArrayBufferIdentity(__alloc(sizeof<f64>() * 6, idof<ArrayBuffer>()))); /** * An operation that generates a DOMMatrix reflecting the current transform on the `_transformStack */ @inline private _getTransform(): DOMMatrix { var result: DOMMatrix = new DOMMatrix(); var stack = this._stack.reference(); result.m11 = stack.a; result.m12 = stack.b; result.m21 = stack.c; result.m22 = stack.d; result.m41 = stack.e; result.m42 = stack.f; return result; } /** * An function that sets the current transform on the `_transformStack` to the specified * DOMMatrix values. * * @param {f64} a - The a property of the transform matrix. * @param {f64} b - The b property of the transform matrix. * @param {f64} c - The c property of the transform matrix. * @param {f64} d - The d property of the transform matrix. * @param {f64} e - The e property of the transform matrix. * @param {f64} f - The f property of the transform matrix. */ @inline private _setTransform(a: f64, b: f64, c: f64, d: f64, e: f64, f: f64): void { var stack = this._stack.reference(); stack.a = a; stack.b = b; stack.c = c; stack.d = d; stack.e = e; stack.f = f; } /** * The CanvasRenderingContext2D.currentTransform property of the Canvas 2D API returns or sets a * DOMMatrix (current specification) object for the current transformation matrix */ public get currentTransform(): DOMMatrix { return this._getTransform(); } public set currentTransform(value: DOMMatrix) { this._setTransform(value.m11, value.m12, value.m21, value.m22, value.m41, value.m42); } /** * The CanvasRenderingContext2D.getTransform() method of the Canvas 2D API gets the current * transformation matrix, and returns a DOMMatrix */ public getTransform(): DOMMatrix { return this._getTransform(); } /** * An internal function that writes the current transform value on the _transformStack to the * buffer if it currently does not match the last written transform. */ private _updateTransform(): void { var stack = this._stack.reference(); var a = stack.a; var b = stack.b; var c = stack.c; var d = stack.d; var e = stack.e; var f = stack.f; var current = changetype<usize>(this._currentTransform); if ( a != LOAD<f64>(current, 0) || b != LOAD<f64>(current, 1) || c != LOAD<f64>(current, 2) || d != LOAD<f64>(current, 3) || e != LOAD<f64>(current, 4) || f != LOAD<f64>(current, 5)) { super._writeSix(CanvasInstruction.SetTransform, a, b, c, d, e, f); STORE<f64>(current, 0, a); STORE<f64>(current, 1, b); STORE<f64>(current, 2, c); STORE<f64>(current, 3, d); STORE<f64>(current, 4, e); STORE<f64>(current, 5, f); } } //#endregion TRANSFORM //#region DIRECTION /** * A private member that contains a single CanvasDirection value that represents the last * CanvasDirection value written by a drawing operation */ private _currentDirection: CanvasDirection = CanvasDirection.inherit; /** * The CanvasRenderingContext2D.direction property of the Canvas 2D API specifies the current text * direction used to draw text */ public get direction(): CanvasDirection { return this._stack.reference().direction; } public set direction(value: CanvasDirection) { this._stack.reference().direction = value; } /** * An internal function that writes the current CanvasDirection value on the _directionStack to * the buffer if it currently does not match the last written CanvasDirection. */ @inline private _updateDirection(): void { var value: CanvasDirection = this._stack.reference().direction; if (value != this._currentDirection) { this._currentDirection = value; super._writeOne(CanvasInstruction.Direction, <f64>value); } } //#endregion DIRECTION //#region FILLSTYLE /** * A private member that contains a single StrokeFillStyleType value that represents the last * fillStyle value written by a drawing operation */ private _currentFillStyleType: FillStrokeStyleType = FillStrokeStyleType.String; /** * A private member that contains a single pointer or id value that represents the last * fillStyle value written by a drawing operation */ private _currentFillStyleValue: usize = changetype<usize>(defaultBlack); /** * The CanvasRenderingContext2D.fillStyle property of the Canvas 2D API specifies the current text * representing a CSS Color */ public get fillStyle(): string | null { var stack = this._stack.reference(); return stack.fillStyleType === FillStrokeStyleType.String ? stack.fillStyleString : null; } public set fillStyle(value: string | null) { if (value == null) value = defaultBlack; let stack = this._stack.reference(); let currentType = stack.fillStyleType; stack.fillStyleType = FillStrokeStyleType.String; __retain(changetype<usize>(value)); if (currentType == FillStrokeStyleType.CanvasGradient) { __release(changetype<usize>(stack.fillStyleGradient)); stack.fillStyleGradient = null; } else if (currentType == FillStrokeStyleType.CanvasPattern) { __release(changetype<usize>(stack.fillStylePattern)); stack.fillStylePattern = null; } else { __release(changetype<usize>(stack.fillStyleString)); } stack.fillStyleString = value!; stack.fillStyleValue = changetype<usize>(value); } /** * An internal function that writes the current fillStyle value on the _fillStyleStack to the * buffer if it currently does not match the last written fillStyle. */ @inline private _updateFillStyle(): void { var stack = this._stack.reference(); var styleType = stack.fillStyleType; var pointer: usize = 0; var value: f64 = 0; if (styleType === FillStrokeStyleType.String) { pointer = changetype<usize>(stack.fillStyleString); value = pointer; } else if (styleType === FillStrokeStyleType.CanvasGradient) { pointer = changetype<usize>(stack.fillStyleGradient); value = <f64>load<i32>(pointer, offsetof<CanvasGradient>("id")); } else if (styleType === FillStrokeStyleType.CanvasPattern) { pointer = changetype<usize>(stack.fillStylePattern); value = <f64>load<i32>(pointer, offsetof<CanvasPattern>("id")); } if (styleType != this._currentFillStyleType || value != this._currentFillStyleValue) { var inst: CanvasInstruction; if (styleType == FillStrokeStyleType.String) inst = CanvasInstruction.FillStyle; else if (styleType == FillStrokeStyleType.CanvasGradient) inst = CanvasInstruction.FillGradient; else inst = CanvasInstruction.FillPattern; super._retain(pointer); super._writeOne(inst, <f64>value); } } //#endregion FILLSTYLE //#region FILLPATTERN /** * The CanvasRenderingContext2D.fillPattern property of the Canvas 2D API specifies the current * fillStyle pattern */ public get fillPattern(): CanvasPattern | null { var stack = this._stack.reference(); return stack.fillStyleType === FillStrokeStyleType.CanvasPattern ? stack.fillStylePattern : null; } public set fillPattern(value: CanvasPattern | null) { if (value == null) { this.fillStyle = defaultBlack; return; } __retain(changetype<usize>(value)); var stack = this._stack.reference(); __release(changetype<usize>(stack.fillStylePattern)); stack.fillStyleType = FillStrokeStyleType.CanvasPattern; stack.fillStylePattern = value; stack.fillStyleValue = <usize>load<i32>(changetype<usize>(value), offsetof<CanvasPattern>("id")); } //#endregion FILLPATTERN //#region FILLGRADIENT /** * The CanvasRenderingContext2D.fillGradient property of the Canvas 2D API specifies the current * fillStyle gradient */ public get fillGradient(): CanvasGradient | null { var stack = this._stack.reference(); return stack.fillStyleType == FillStrokeStyleType.CanvasGradient ? stack.fillStyleGradient : null; } public set fillGradient(value: CanvasGradient | null) { if (value == null) { this.fillStyle = defaultBlack; return; } __retain(changetype<usize>(value)); var stack = this._stack.reference(); stack.fillStyleType = FillStrokeStyleType.CanvasGradient; __release(changetype<usize>(stack.fillStyleGradient)); stack.fillStyleGradient = value; stack.fillStyleValue = <usize>load<i32>(changetype<usize>(value), offsetof<CanvasGradient>("id")); } //#endregion FILLGRADIENT //#region CREATEPATTERN /** * The CanvasRenderingContext2D.createPattern() method of the Canvas 2D API creates a pattern * using the specified image and repetition. * * @param {Image} img - A CanvasImageSource to be used as the pattern's Image. * @param {CanvasPatternRepetition} repetition - An enum value indicating how to repeat the pattern's image. */ public createPattern(img: Image, repetition: CanvasPatternRepetition): CanvasPattern { var result = new CanvasPattern(); var id: i32 = load<i32>(changetype<usize>(img), offsetof<Image>("_id")); store<i32>(changetype<usize>(result), createPattern(this.id, id, repetition), offsetof<CanvasPattern>("id")); return result; } //#endregion CREATEPATTERN //#region FILTER /** * A private member that contains a single string value that represents the last * filter value written by a drawing operation. */ private _currentFilter: string = defaultNone; /** * The CanvasRenderingContext2D.filter property of the Canvas 2D API provides filter effects such * as blurring and grayscaling. It is similar to the CSS filter property and accepts the same * values. */ public get filter(): string { return this._stack.reference().filter; } public set filter(value: string) { let stack = this._stack.reference(); __retain(changetype<usize>(value)); __release(changetype<usize>(stack.filter)); stack.filter = value; } /** * An internal function that writes the current filter value on the _filterStack if it currently * does not match the last written filter string value to the buffer using write_one. */ @inline private _updateFilter(): void { var value: string = this._stack.reference().filter; if (value != this._currentFilter) { this._currentFilter = value; super._retain(changetype<usize>(value)); super._writeOne(CanvasInstruction.Filter, changetype<usize>(value)); } } //#endregion FILTER //#region FONT /** * A private member that contains a single string value that represents the last * font value written by a drawing operation. */ private _currentFont: string = defaultFont; /** * The CanvasRenderingContext2D.font property of the Canvas 2D API specifies the current text * style to use when drawing text. This string uses the same syntax as the CSS font specifier. */ public get font(): string { return this._stack.reference().font; } public set font(value: string) { let stack = this._stack.reference(); __retain(changetype<usize>(value)); __release(changetype<usize>(stack.font)); stack.font = value; } /** * An internal function that writes the current font value on the _fontStack to the buffer if it * currently does not match the last written font string value. */ @inline private _updateFont(): void { var value: string = this._stack.reference().font; if (value != this._currentFont) { this._currentFont = value; super._retain(changetype<usize>(value)); super._writeOne(CanvasInstruction.Font, changetype<usize>(value)); } } //#endregion FONT //#region GLOBALALPHA /** * A private member that contains a single float value that represents the last globalAlpha value * written by a drawing operation. */ private _currentGlobalAlpha: f64 = 1.0; /** * The CanvasRenderingContext2D.globalAlpha property of the Canvas 2D API specifies the alpha * (transparency) value that is applied to shapes and images before they are drawn onto the * canvas. */ public get globalAlpha(): f64 { return this._stack.reference().globalAlpha; } public set globalAlpha(value: f64) { if (!isFinite(value) || value < 0.0 || value > 1.0) return; this._stack.reference().globalAlpha = value; } /** * An internal function that writes the current globalAlpha value on the _globalAlphaStack to the * buffer if it currently does not match the last written globalAlpha value. */ @inline private _updateGlobalAlpha(): void { var value: f64 = this._stack.reference().globalAlpha; if (value != this._currentGlobalAlpha) { this._currentGlobalAlpha = value; super._writeOne(CanvasInstruction.GlobalAlpha, value); } } //#endregion GLOBALALPHA //#region GLOBALCOMPOSITEOPERATION /** * A private member that contains a single GlobalCompositeOperation value that represents the last * globalCompositeOperation value written by a drawing operation. */ private _currentGlobalCompositeOperation: GlobalCompositeOperation = GlobalCompositeOperation.source_over; /** * The CanvasRenderingContext2D.globalCompositeOperation property of the Canvas 2D API sets the * type of compositing operation to apply when drawing new shapes. */ public get globalCompositeOperation(): GlobalCompositeOperation { return this._stack.reference().globalCompositeOperation; } public set globalCompositeOperation(value: GlobalCompositeOperation) { this._stack.reference().globalCompositeOperation = value; } /** * An internal function that writes the current globalCompositeOperation value on the * _globalCompositeOperationStack to the buffer if it currently does not match the last written * globalCompositeOperation value. */ @inline private _updateGlobalCompositeOperation(): void { var value: GlobalCompositeOperation = this._stack.reference().globalCompositeOperation; if (value != this._currentGlobalCompositeOperation) { this._currentGlobalCompositeOperation = value; super._writeOne(CanvasInstruction.GlobalCompositeOperation, <f64>value); } } //#endregion GLOBALCOMPOSITEOPERATION //#region IMAGESMOOTHINGENABLED /** * A private member that contains a single bool value that represents the last * imageSmoothingEnabled value written by a drawing operation. */ private _currentImageSmoothingEnabled: bool = true; /** * The imageSmoothingEnabled property of the CanvasRenderingContext2D interface, part of the * Canvas API, determines whether scaled images are smoothed (true, default) or not (false). On * getting the imageSmoothingEnabled property, the last value it was set to is returned. */ public get imageSmoothingEnabled(): bool { return this._stack.reference().imageSmoothingEnabled; } public set imageSmoothingEnabled(value: bool) { this._stack.reference().imageSmoothingEnabled = value; } /** * An internal function that writes the current imageSmoothingEnabled value on the * _imageSmoothingEnabledStack to the buffer if it currently does not match the last written * imageSmoothingEnabled value. */ @inline private _updateImageSmoothingEnabled(): void { var value: bool = this._stack.reference().imageSmoothingEnabled; if (value != this._currentImageSmoothingEnabled) { this._currentImageSmoothingEnabled = value; super._writeOne(CanvasInstruction.ImageSmoothingEnabled, value ? 1.0 : 0.0); } } //#endregion IMAGESMOOTHINGENABLED //#region IMAGESMOOTHINGQUALITY /** * A private member that contains a single ImageSmoothingQuality value that represents the last * imageSmoothingQuality value written by a drawing operation. */ private _currentImageSmoothingQuality: ImageSmoothingQuality = ImageSmoothingQuality.low; /** * The imageSmoothingQuality property of the CanvasRenderingContext2D interface, part of the * Canvas API, lets you set the quality of image smoothing. */ public get imageSmoothingQuality(): ImageSmoothingQuality { return this._stack.reference().imageSmoothingQuality; } public set imageSmoothingQuality(value: ImageSmoothingQuality) { this._stack.reference().imageSmoothingQuality = value; } /** * An internal function that writes the current imageSmoothingQuality value on the * _imageSmoothingQualityStack to the buffer if it currently does not match the last written * imageSmoothingQuality value, and imageSmoothingEnabled is true. */ @inline private _updateImageSmoothingQuality(): void { let stack = this._stack.reference(); let enabled = stack.imageSmoothingEnabled; if (enabled) { let value = stack.imageSmoothingQuality; if (value != this._currentImageSmoothingQuality) { this._currentImageSmoothingQuality = value; super._writeOne(CanvasInstruction.ImageSmoothingQuality, <f64>value); } } } //#endregion IMAGESMOOTHINGQUALITY //#region LINECAP /** * A private member that contains a single LineCap value that represents the last * lineCap value written by a drawing operation. */ private _currentLineCap: LineCap = LineCap.butt; /** * The CanvasRenderingContext2D.lineCap property of the Canvas 2D API determines the shape used * to draw the end points of lines. */ public get lineCap(): LineCap { return this._stack.reference().lineCap; } public set lineCap(value: LineCap) { this._stack.reference().lineCap = value; } /** * An internal function that writes the current lineCap value on the _lineCapStack to the buffer * if it currently does not match the last written lineCap value. */ @inline private _updateLineCap(): void { var value: LineCap = this._stack.reference().lineCap; if (value != this._currentLineCap) { this._currentLineCap = value; super._writeOne(CanvasInstruction.LineCap, <f64>value); } } //#endregion LINECAP //#region LINEDASH /** * A private member that contains a single LineCap value that represents the last * lineCap value written by a drawing operation. */ private _currentLineDash: Float64Array = defaultLineDash; /** * The getLineDash() method of the Canvas 2D API's CanvasRenderingContext2D interface gets the * current line dash pattern. */ public getLineDash(): Float64Array { return this._getLineDash(); } /** * The setLineDash() method of the Canvas 2D API's CanvasRenderingContext2D interface sets the * line dash pattern used when stroking lines. It uses a Float64Array of values that specify * alternating lengths of lines and gaps which describe the pattern. * * @param {Float64Array} value - An Array of numbers that specify distances to alternately draw a * line and a gap (in coordinate space units). If the number of elements in the array is odd, the * elements of the array get copied and concatenated. For example, Float64Array [5, 15, 25] will * become Float64Array [5, 15, 25, 5, 15, 25]. If the array is empty, the line dash list is * cleared and line strokes return to being solid. */ public setLineDash(value: Float64Array): void { let stack = this._stack.reference(); __release(changetype<usize>(stack.lineDash)); __retain(changetype<usize>(value)); stack.lineDash = value; } /** * An internal getLineDash function that loops backwards from the current stackOffset until it * doesn't find a null pointer, then returns the reference. */ @inline private _getLineDash(): Float64Array { return this._stack.reference().lineDash; } /** * An internal function that writes the current lineDash value on the _lineDashStack to the buffer * if it currently does not match the last written lineCap value. */ @inline private _updateLineDash(): void { var lineDash: Float64Array = this._getLineDash(); var current: Float64Array = this._currentLineDash; if (!arraysEqual(current, lineDash)) { this._currentLineDash = lineDash; let pointer = changetype<usize>(lineDash); super._retain(pointer); super._writeOne(CanvasInstruction.LineDash, <f64>pointer); } } //#endregion LINEDASH //#region LINEDASHOFFSET /** * A private member that contains a single float value that represents the last lineDashOffset value * written by a drawing operation. */ private _currentLineDashOffset: f64 = 0.0; /** * The CanvasRenderingContext2D.lineDashOffset property of the Canvas 2D API sets the line dash * offset, or "phase." */ public get lineDashOffset(): f64 { return this._stack.reference().lineDashOffset; } public set lineDashOffset(value: f64) { if (!isFinite(value)) return; this._stack.reference().lineDashOffset = value; } /** * An internal function that writes the current lineDashOffset value on the _lineDashOffsetStack * to the buffer if it currently does not match the last written lineDashOffset value. */ @inline private _updateLineDashOffset(): void { var value: f64 = this._stack.reference().lineDashOffset; if (value != this._currentLineDashOffset) { this._currentLineDashOffset = value; super._writeOne(CanvasInstruction.LineDashOffset, value); } } //#endregion LINEDASHOFFSET //#region LINEJOIN /** * A private member that contains a single LineJoin value that represents the last * lineJoin value written by a drawing operation. */ private _currentLineJoin: LineJoin = LineJoin.miter; /** * The CanvasRenderingContext2D.lineJoin property of the Canvas 2D API determines the shape used * to join two line segments where they meet. * * This property has no effect wherever two connected segments have the same direction, because * no joining area will be added in this case. Degenerate segments with a length of zero (i.e., * with all endpoints and control points at the exact same position) are also ignored. */ public get lineJoin(): LineJoin { return this._stack.reference().lineJoin; } public set lineJoin(value: LineJoin) { this._stack.reference().lineJoin = value; } /** * An internal function that writes the current lineJoin value on the _lineJoinStack if it * currently does not match the last written lineJoin value. */ @inline private _updateLineJoin(): void { var value: LineJoin = this._stack.reference().lineJoin; if (value != this._currentLineJoin) { this._currentLineJoin = value; super._writeOne(CanvasInstruction.LineJoin, <f64>value); } } //#endregion //#region LINEWIDTH /** * A private member that contains a single float value that represents the last lineWidth value * written by a drawing operation. */ private _currentLineWidth: f64 = 1.0; /** * The CanvasRenderingContext2D.lineWidth property of the Canvas 2D API sets the line dash * offset, or "phase." */ public get lineWidth(): f64 { return this._stack.reference().lineWidth; } public set lineWidth(value: f64) { if (!isFinite(value) || value < 0) return; this._stack.reference().lineWidth = value; } /** * An internal function that writes the current lineWidth value on the _lineWidthStack to the * buffer if it currently does not match the last written lineWidth value. */ @inline private _updateLineWidth(): void { var value: f64 = this._stack.reference().lineWidth; if (value != this._currentLineWidth) { this._currentLineWidth = value; super._writeOne(CanvasInstruction.LineWidth, value); } } //#endregion //#region MITERLIMIT /** * A private member that contains a single float value that represents the last miterLimit value * written by a drawing operation. */ private _currentMiterLimit: f64 = 10.0; /** * The CanvasRenderingContext2D.miterLimit property of the Canvas 2D API sets the miter limit * ratio. It establishes a limit on the miter when two lines join at a sharp angle, to let you * control how thick the junction becomes. */ public get miterLimit(): f64 { return this._stack.reference().miterLimit; } public set miterLimit(value: f64) { if (!isFinite(value) || value < 0) return; this._stack.reference().miterLimit = value; } /** * An internal function that writes the current miterLimit value on the _miterLimitStack to the * buffer if it currently does not match the last written miterLimit value. */ @inline private _updateMiterLimit(): void { var value: f64 = this._stack.reference().miterLimit; if (value != this._currentMiterLimit) { this._currentMiterLimit = value; super._writeOne(CanvasInstruction.MiterLimit, value); } } //#endregion MITERLIMIT //#region SHADOWBLUR /** * A private member that contains a single float value that represents the last shadowBlur value * written by a drawing operation. */ private _currentShadowBlur: f64 = 0.0; /** * The CanvasRenderingContext2D.shadowBlur property of the Canvas 2D API specifies the amount of * blur applied to shadows. The default is 0 (no blur). * * The shadowBlur value is a non-negative float specifying the level of shadow blur, where 0 * represents no blur and larger numbers represent increasingly more blur. This value doesn't * correspond to a number of pixels, and is not affected by the current transformation matrix. The * default value is 0. Negative, Infinity, and NaN values are ignored. */ public get shadowBlur(): f64 { return this._stack.reference().shadowBlur; } public set shadowBlur(value: f64) { if (!isFinite(value) || value < 0) return; this._stack.reference().shadowBlur = value; } /** * An internal function that writes the current shadowBlur value on the _shadowBlurStack to the * buffer if it currently does not match the last written shadowBlur value. */ @inline private _updateShadowBlur(): void { var value: f64 = this._stack.reference().shadowBlur; if (value != this._currentShadowBlur) { this._currentShadowBlur = value; super._writeOne(CanvasInstruction.ShadowBlur, value); } } //#endregion SHADOWBLUR //#region SHADOWCOLOR /** * A private member that contains a single StrokeShadowColorType value that represents the last * shadowColor value written by a drawing operation */ private _currentShadowColor: string = defaultShadowColor; /** * The CanvasRenderingContext2D.shadowColor property of the Canvas 2D API specifies the current text * representing a CSS Color */ public get shadowColor(): string { return this._stack.reference().shadowColor; } public set shadowColor(value: string) { if (value == null) value = defaultShadowColor; var stack = this._stack.reference(); __retain(changetype<usize>(value)); __release(changetype<usize>(stack.shadowColor)); stack.shadowColor = value; } /** * An internal function that writes the current shadowColor value on the _shadowColorStack to the * buffer if it currently does not match the last written shadowColor. */ @inline private _updateShadowColor(): void { var value: string = this._stack.reference().shadowColor; if (value != this._currentShadowColor) { this._currentFilter = value; super._retain(changetype<usize>(value)); super._writeOne(CanvasInstruction.ShadowColor, changetype<usize>(value)); } } //#endregion //#region SHADOWOFFSETX /** * A private member that contains a single float value that represents the last shadowOffsetX value * written by a drawing operation. */ private _currentShadowOffsetX: f64 = 0.0; /** * The CanvasRenderingContext2D.shadowOffsetX property of the Canvas 2D API specifies the distance * that shadows will be offset horizontally. * * The value is a f64 specifying the distance that shadows will be offset horizontally. Positive * values are to the right, and negative to the left. The default value is 0 (no horizontal * offset). Infinity and NaN values are ignored. */ public get shadowOffsetX(): f64 { return this._stack.reference().shadowOffsetX; } public set shadowOffsetX(value: f64) { if (!isFinite(value)) return; this._stack.reference().shadowOffsetX = value; } /** * An internal function that writes the current shadowOffsetX value on the _shadowOffsetXStack to the * buffer if it currently does not match the last written shadowOffsetX value. */ @inline private _updateShadowOffsetX(): void { var value: f64 = this._stack.reference().shadowOffsetX; if (value != this._currentShadowOffsetX) { this._currentShadowOffsetX = value; super._writeOne(CanvasInstruction.ShadowOffsetX, value); } } //#endregion SHADOWOFFSETX //#region SHADOWOFFSETY /** * A private member that contains a single float value that represents the last shadowOffsetY value * written by a drawing operation. */ private _currentShadowOffsetY: f64 = 0.0; /** * The CanvasRenderingContext2D.shadowOffsetY property of the Canvas 2D API specifies the distance * that shadows will be offset vertically. * * The value is a f64 specifying the distance that shadows will be offset horizontally. Positive * values are down, and negative are up. The default value is 0 (no vertical offset). Infinity and * NaN values are ignored */ public get shadowOffsetY(): f64 { return this._stack.reference().shadowOffsetY; } public set shadowOffsetY(value: f64) { if (!isFinite(value)) return; this._stack.reference().shadowOffsetY = value; } /** * An internal function that writes the current shadowOffsetY value on the _shadowOffsetYStack to the * buffer if it currently does not match the last written shadowOffsetY value. */ @inline private _updateShadowOffsetY(): void { var value: f64 = this._stack.reference().shadowOffsetY; if (value != this._currentShadowOffsetY) { this._currentShadowOffsetY = value; super._writeOne(CanvasInstruction.ShadowOffsetY, value); } } //#endregion SHADOWOFFSETY //#region STROKESTYLE /** * A private member that contains a single StrokeFillStyleType value that represents the last * strokeStyle value written by a drawing operation */ private _currentStrokeStyleType: FillStrokeStyleType = FillStrokeStyleType.String; /** * A private member that contains a single pointer or id value that represents the last * fillStyle value written by a drawing operation */ private _currentStrokeStyleValue: usize = changetype<usize>(defaultBlack); /** * The CanvasRenderingContext2D.strokeStyle property of the Canvas 2D API specifies the current text * representing a CSS Color */ public get strokeStyle(): string | null { var stack = this._stack.reference(); return stack.strokeStyleType === FillStrokeStyleType.String ? stack.strokeStyleString : null; } public set strokeStyle(value: string | null) { if (value == null) value = defaultBlack; let stack = this._stack.reference(); let currentType = stack.strokeStyleType; stack.strokeStyleType = FillStrokeStyleType.String; __retain(changetype<usize>(value)); if (currentType == FillStrokeStyleType.CanvasGradient) { __release(changetype<usize>(stack.strokeStyleGradient)); stack.strokeStyleGradient = null; } else if (currentType == FillStrokeStyleType.CanvasPattern) { __release(changetype<usize>(stack.strokeStylePattern)); stack.strokeStylePattern = null; } else { __release(changetype<usize>(stack.strokeStyleString)); } stack.strokeStyleString = value!; stack.strokeStyleValue = changetype<usize>(value); } /** * An internal function that writes the current strokeStyle value on the _strokeStyleStack to the * buffer if it currently does not match the last written strokeStyle. */ @inline private _updateStrokeStyle(): void { var stack = this._stack.reference(); var styleType = stack.strokeStyleType; var pointer: usize = 0; var value: f64 = 0; if (styleType === FillStrokeStyleType.String) { pointer = changetype<usize>(stack.strokeStyleString); value = pointer; } else if (styleType === FillStrokeStyleType.CanvasGradient) { pointer = changetype<usize>(stack.strokeStyleGradient); value = <f64>load<i32>(pointer, offsetof<CanvasGradient>("id")); } else if (styleType === FillStrokeStyleType.CanvasPattern) { pointer = changetype<usize>(stack.strokeStylePattern); value = <f64>load<i32>(pointer, offsetof<CanvasPattern>("id")); } if (styleType != this._currentStrokeStyleType || value != this._currentStrokeStyleValue) { var inst: CanvasInstruction; if (styleType == FillStrokeStyleType.String) inst = CanvasInstruction.StrokeStyle; else if (styleType == FillStrokeStyleType.CanvasGradient) inst = CanvasInstruction.StrokeGradient; else inst = CanvasInstruction.StrokePattern; super._retain(pointer); super._writeOne(inst, <f64>value); } } //#endregion STROKESTYLE //#region STROKEPATTERN /** * The CanvasRenderingContext2D.strokePattern property of the Canvas 2D API specifies the current * strokeStyle pattern */ public get strokePattern(): CanvasPattern | null { var stack = this._stack.reference(); return stack.strokeStyleType === FillStrokeStyleType.CanvasPattern ? stack.strokeStylePattern : null; } public set strokePattern(value: CanvasPattern | null) { if (value == null) { this.strokeStyle = defaultBlack; return; } __retain(changetype<usize>(value)); var stack = this._stack.reference(); __release(changetype<usize>(stack.strokeStylePattern)); stack.strokeStyleType = FillStrokeStyleType.CanvasPattern; stack.strokeStylePattern = value; stack.strokeStyleValue = <usize>load<i32>(changetype<usize>(value), offsetof<CanvasPattern>("id")); } //#endregion STROKEPATTERN //#region STROKEGRADIENT /** * The CanvasRenderingContext2D.strokeGradient property of the Canvas 2D API specifies the current * strokeStyle gradient. */ public get strokeGradient(): CanvasGradient | null { var stack = this._stack.reference(); return stack.strokeStyleType == FillStrokeStyleType.CanvasGradient ? stack.strokeStyleGradient : null; } public set strokeGradient(value: CanvasGradient | null) { if (value == null) { this.strokeStyle = defaultBlack; return; } __retain(changetype<usize>(value)); var stack = this._stack.reference(); stack.strokeStyleType = FillStrokeStyleType.CanvasGradient; __release(changetype<usize>(stack.strokeStyleGradient)); stack.strokeStyleGradient = value; stack.strokeStyleValue = <usize>load<i32>(changetype<usize>(value), offsetof<CanvasGradient>("id")); } //#endregion STROKEGRADIENT //#region TEXTALIGN /** * A private member that contains a single LineCap value that represents the last * lineCap value written by a drawing operation. */ private _currentTextAlign: TextAlign = TextAlign.start; /** * The CanvasRenderingContext2D.textAlign property of the Canvas 2D API specifies the current text * alignment used when drawing text. * * The alignment is relative to the x value of the fillText() method. For example, if textAlign is * "center", then the text's left edge will be at x - (textWidth / 2). */ public get textAlign(): TextAlign { return this._stack.reference().textAlign; } public set textAlign(value: TextAlign) { this._stack.reference().textAlign = value; } /** * An internal function that writes the current textAlign value on the _textAlignStack to the * buffer if it currently does not match the last written textAlign value. */ @inline private _updateTextAlign(): void { var value: TextAlign = this._stack.reference().textAlign; if (value != this._currentTextAlign) { this._currentTextAlign = value; super._writeOne(CanvasInstruction.TextAlign, <f64>value); } } //#endregion TEXTALIGN //#region TEXTBASELINE /** * A private member that contains a single TextBaseline value that represents the last * TextBaseline value written by a drawing operation. */ private _currentTextBaseline: TextBaseline = TextBaseline.alphabetic; /** * The CanvasRenderingContext2D.textBaseline property of the Canvas 2D API specifies the current * text baseline used when drawing text. */ public get textBaseline(): TextBaseline { return this._stack.reference().textBaseline; } public set textBaseline(value: TextBaseline) { this._stack.reference().textBaseline = value; } /** * An internal function that writes the current textBaseline value on the _textBaselineStack to the * buffer if it currently does not match the last written textBaseline value. */ @inline private _updateTextBaseline(): void { var value: TextBaseline = this._stack.reference().textBaseline; if (value != this._currentTextBaseline) { this._currentTextBaseline = value; super._writeOne(CanvasInstruction.TextBaseline, <f64>value); } } //#endregion TEXTBASELINE //#region SAVE /** * The CanvasRenderingContext2D.save() method of the Canvas 2D API saves the entire state of the * canvas by pushing the current state onto a stack. * * The drawing state that gets saved onto a stack consists of: * * - The current transformation matrix. * - The current clipping region. * - The current dash list. * - The current values of the following attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled. * * @param {bool} hard - Tells the context to perform an actual `save()` operation. Default value is false. */ public save(hard: bool = false): void { var offset: i32 = <i32>this._stackOffset; var nextOffset: i32 = offset + 1; if (nextOffset >= <i32>u8.MAX_VALUE) unreachable(); let stack = this._stack.push(); this._stack = stack; let stackReference = stack.reference(); // hard saves stackReference.save = hard; // fillStyle __retain(changetype<usize>(stackReference.fillStyleGradient)); __retain(changetype<usize>(stackReference.fillStylePattern)); __retain(changetype<usize>(stackReference.fillStyleString)); // filter __retain(changetype<usize>(stackReference.filter)); // font __retain(changetype<usize>(stackReference.font)); // lineDash __retain(changetype<usize>(stackReference.lineDash)); // shadowColor __retain(changetype<usize>(stackReference.shadowColor)); // strokeStyle __retain(changetype<usize>(stackReference.strokeStyleGradient)); __retain(changetype<usize>(stackReference.strokeStylePattern)); __retain(changetype<usize>(stackReference.strokeStyleString)); if (hard) super._writeZero(CanvasInstruction.Save); this._stackOffset = <u8>nextOffset; } //#endregion SAVE //#region RESTORE /** * The CanvasRenderingContext2D.restore() method of the Canvas 2D API restores the most recently * saved canvas state by popping the top entry in the drawing state stack. If there is no saved * state, this method does nothing. * * In the case of the hard restore, this function will mirror what the browser does, and modifies * the last written values instead of just moving the stack pointer. This ensures that the writer * emulates the browser state machine as accurately as possible. */ public restore(): void { if (this._stackOffset == <u8>0) return; let currentStack = this._stack; let nextStack = currentStack.pop(); this._stack = nextStack; let currentStackReference = currentStack.reference(); let nextStackReference = nextStack.reference(); // fillStyle __release(changetype<usize>(currentStackReference.fillStyleGradient)); __release(changetype<usize>(currentStackReference.fillStylePattern)); __release(changetype<usize>(currentStackReference.fillStyleString)); // filter __release(changetype<usize>(currentStackReference.filter)); // font __release(changetype<usize>(currentStackReference.font)); // lineDash __release(changetype<usize>(currentStackReference.lineDash)); // shadowColor __release(changetype<usize>(currentStackReference.shadowColor)); // strokeStyle __release(changetype<usize>(currentStackReference.strokeStyleGradient)); __release(changetype<usize>(currentStackReference.strokeStylePattern)); __release(changetype<usize>(currentStackReference.strokeStyleString)); if (currentStackReference.save) { super._writeZero(CanvasInstruction.Restore); // currentTransform memory.copy( changetype<usize>(this._currentTransform), changetype<usize>(nextStackReference) + offsetof<CanvasStack>("a"), 48, ); this._currentDirection = nextStackReference.direction; this._currentFillStyleType = nextStackReference.fillStyleType; this._currentFillStyleValue = <usize>nextStackReference.fillStyleValue; this._currentFilter = nextStackReference.filter; this._currentFont = nextStackReference.font; this._currentGlobalAlpha = nextStackReference.globalAlpha; this._currentGlobalCompositeOperation = nextStackReference.globalCompositeOperation; this._currentImageSmoothingEnabled = nextStackReference.imageSmoothingEnabled; this._currentImageSmoothingQuality = nextStackReference.imageSmoothingQuality; this._currentLineCap = nextStackReference.lineCap; this._currentLineDash = nextStackReference.lineDash; this._currentLineJoin = nextStackReference.lineJoin; this._currentLineWidth = nextStackReference.lineWidth; this._currentMiterLimit = nextStackReference.miterLimit; this._currentShadowBlur = nextStackReference.shadowBlur; this._currentShadowColor = nextStackReference.shadowColor; this._currentShadowOffsetX = nextStackReference.shadowOffsetX; this._currentShadowOffsetY = nextStackReference.shadowOffsetY; this._currentStrokeStyleType = nextStackReference.strokeStyleType; this._currentStrokeStyleValue = <usize>nextStackReference.strokeStyleValue; this._currentTextAlign = nextStackReference.textAlign; this._currentTextBaseline = nextStackReference.textBaseline; } this._stackOffset -= <u8>1; } //#endregion RESTORE //#region PATH /** * A c like pointer that always points to the next path element to write to. */ private _path: StackPointer<Path2DElement> = createPathElements().increment(); /** * A reference to the path start for quick path resetting. */ private _pathStart: StackPointer<Path2DElement> = this._path.decrement(); /** * A pointer that points to the end of the path. */ private _pathEnd: StackPointer<Path2DElement> = changetype<StackPointer<Path2DElement>>(changetype<usize>(this._pathStart) + offsetof<Path2DElement>() * 0x1000); /** * A reference to the next path item that should be written to the buffer. */ private _pathCurrent: StackPointer<Path2DElement> = this._pathStart; /** * An internal function that writes a single path item to the _path. * * @param {CanvasInstruction} inst - The CanvasInstruction that represents the current pathing * operation that should be written to the path buffer. * @param {bool} updateTransform - The bool value that determines if the PathElement should store * the _currentTransform values. * @param {i32} count - The number of parameters for this PathElement's instruction. * @param {f64} a - The first parameter for this PathElement's instruction. * @param {f64} b - The second parameter for this PathElement's instruction. * @param {f64} c - The third parameter for this PathElement's instruction. * @param {f64} d - The fourth parameter for this PathElement's instruction. * @param {f64} e - The five parameter for this PathElement's instruction. * @param {f64} f - The six parameter for this PathElement's instruction. * @param {f64} g - The seven parameter for this PathElement's instruction. * @param {f64} h - The eighth parameter for this PathElement's instruction. */ @inline private _writePath( inst: CanvasInstruction, updateTransform: bool = false, count: i32 = 0, a: f64 = 0.0, b: f64 = 0.0, c: f64 = 0.0, d: f64 = 0.0, e: f64 = 0.0, f: f64 = 0.0, g: f64 = 0.0, h: f64 = 0.0, ): void { let _path = this._path; let element = _path.reference(); assert(changetype<usize>(_path) < changetype<usize>(this._pathEnd)); element.instruction = inst; element.updateTransform = updateTransform; if (updateTransform) { let current = this._stack.reference(); element.transformA = current.a; element.transformB = current.b; element.transformC = current.c; element.transformD = current.d; element.transformE = current.e; element.transformF = current.f; } element.count = count; element.a = a; element.b = b; element.c = c; element.d = d; element.e = e; element.f = f; element.g = g; element.h = h; this._path = _path.increment(); } /** * An internal function that writes the queued up path items to the buffer. It optionally calls * setTransform if the transform was modified between path calls. */ @inline private _updatePath(): void { var nextPath = this._path; var el: Path2DElement; var a: f64; var b: f64; var c: f64; var d: f64; var e: f64; var f: f64; var currentTransform: usize = changetype<usize>(this._currentTransform); var currentPath = this._pathCurrent; while (currentPath.dereference() < nextPath.dereference()) { el = currentPath.reference(); if (el.updateTransform) { a = el.transformA; b = el.transformB; c = el.transformC; d = el.transformD; e = el.transformE; f = el.transformF; let diff = memory.compare( currentTransform, changetype<usize>(el) + offsetof<Path2DElement>("transformA"), 48, ); if (diff != 0) { super._writeSix(CanvasInstruction.SetTransform, a, b, c, d, e, f); STORE<f64>(currentTransform, 0, a); STORE<f64>(currentTransform, 1, b); STORE<f64>(currentTransform, 2, c); STORE<f64>(currentTransform, 3, d); STORE<f64>(currentTransform, 4, e); STORE<f64>(currentTransform, 5, f); } } switch (el.count) { case 0: { super._writeZero(el.instruction); break; } case 1: { super._writeOne(el.instruction, el.a); break; } case 2: { super._writeTwo(el.instruction, el.a, el.b); break; } case 4: { super._writeFour(el.instruction, el.a, el.b, el.c, el.d); break; } case 5: { super._writeFive(el.instruction, el.a, el.b, el.c, el.d, el.e); break; } case 6: { super._writeSix(el.instruction, el.a, el.b, el.c, el.d, el.e, el.f); break; } case 8: { super._writeEight(el.instruction, el.a, el.b, el.c, el.d, el.e, el.f, el.g, el.h); } } currentPath = currentPath.increment(); } this._pathCurrent = currentPath; } //#endregion PATH //#region ARC /** * The CanvasRenderingContext2D.arc() method of the Canvas 2D API adds a circular arc to * the current sub-path. * * @param {f64} x - The x-axis (horizontal) coordinate of the arc's center. * @param {f64} y - The y-axis (vertical) coordinate of the arc's center. * @param {f64} radius - The arc's radius. Must be non-negative. * @param {f64} startAngle - The angle at which the arc starts, measured clockwise from the positive x-axis * and expressed in radians. * @param {f64} endAngle - The angle at which the arc ends, measured clockwise from the positive x-axis and * expressed in radians. * @param {bool} anticlockwise - An optional bool which, if true, causes the arc to be drawn * counter-clockwise between the start and end angles. The default value is false (clockwise). */ public arc(x: f64, y: f64, radius: f64, startAngle: f64, endAngle: f64 , anticlockwise: bool = false): void { if (!isFinite(x + y + radius + startAngle + endAngle) || radius < 0) return; this._writePath(CanvasInstruction.Arc, true, 6, x, y, radius, startAngle, endAngle, anticlockwise ? 1.0 : 0.0); } //#endregion ARC //#region ARCTO /** * The CanvasRenderingContext2D.arcTo() method of the Canvas 2D API adds a circular arc to the current * sub-path, using the given control points and radius. The arc is automatically connected to the * path's latest point with a straight line, if necessary for the specified parameters. This method is * commonly used for making rounded corners. * * @param {f64} x1 - The x-axis coordinate of the first control point. * @param {f64} y1 - The y-axis coordinate of the first control point. * @param {f64} x2 - The x-axis coordinate of the second control point. * @param {f64} y2 - The y-axis coordinate of the second control point. * @param {f64} radius - The arc's radius. Must be non-negative. */ public arcTo(x1: f64, y1: f64, x2: f64, y2: f64, radius: f64): void { if (!isFinite(x1 + y1 + x2 + y2 + radius) || radius < 0) return; this._writePath(CanvasInstruction.ArcTo, true, 5, x1, y1, x2, y2, radius); } //#endregion ARCTO //#region BEGINPATH /** * The CanvasRenderingContext2D.beginPath() method of the Canvas 2D API starts a new path by * emptying the list of sub-paths. Call this method when you want to create a new path. */ public beginPath(): void { let start = this._pathStart; this._path = start.increment(); this._pathCurrent = start; } //#endregion BEGINPATH //#region BEZIERCURVETO /** * The CanvasRenderingContext2D.bezierCurveTo() method of the Canvas 2D API adds a cubic Bézier * curve to the current sub-path. It requires three points: the first two are control points and * the third one is the end point. The starting point is the latest point in the current path, which * can be changed using moveTo() before creating the Bézier curve. * * @param {f64} cp1x - The x-axis coordinate of the first control point. * @param {f64} cp1y - The y-axis coordinate of the first control point. * @param {f64} cp2x - The x-axis coordinate of the second control point. * @param {f64} cp2y - The y-axis coordinate of the second control point. * @param {f64} x - The x-axis coordinate of the end point. * @param {f64} y - The y-axis coordinate of the end point. */ public bezierCurveTo(cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, x: f64, y: f64): void { if (!isFinite(cp1x + cp1y + cp2x + cp2y + x + y)) return; this._writePath(CanvasInstruction.BezierCurveTo, true, 6, cp1x, cp1y, cp2x, cp2y, x, y); } //#endregion BEZIERCURVETO //#region CLEARRECT /** * The CanvasRenderingContext2D.clearRect() method of the Canvas 2D API erases the pixels in a * rectangular area by setting them to transparent black. * * @param {f64} x - The x-axis coordinate of the rectangle's starting point. * @param {f64} y - The y-axis coordinate of the rectangle's starting point. * @param {f64} width - The rectangle's width. Positive values are to the right, and negative to * the left. * @param {f64} height - The rectangle's height. Positive values are down, and negative are up. */ public clearRect(x: f64, y: f64, width: f64, height: f64): void { if (!isFinite(x + y + width + height)) return; this._updateTransform(); super._writeFour(CanvasInstruction.ClearRect, x, y, width, height); } //#endregion CLEARRECT //#region CLIP /** * The CanvasRenderingContext2D.clip() method of the Canvas 2D API turns the current or given path * into the current clipping region. It replaces any previous clipping region. In the image below, * the red outline represents a clipping region shaped like a star. Only those parts of the * checkerboard pattern that are within the clipping region get drawn. */ public clip(): void { this._updatePath(); super._writeZero(CanvasInstruction.Clip); } //#endregion CLIP //#region CLOSEPATH /** * The CanvasRenderingContext2D.closePath() method of the Canvas 2D API attempts to add a straight * line from the current point to the start of the current sub-path. If the shape has already been * closed or has only one point, this function does nothing. This method doesn't draw anything to * the canvas directly. You can render the path using the stroke() or fill() methods. */ public closePath(): void { let previous = this._path.decrement().reference(); if (i32(previous.instruction == CanvasInstruction.BeginPath) | i32(previous.instruction == CanvasInstruction.ClosePath)) return; this._writePath(CanvasInstruction.ClosePath, true, 0); } //#endregion CLOSEPATH //#region DRAWIMAGE /** * The CanvasRenderingContext2D.drawImagePosition() method of the Canvas 2D API provides a simple * method for drawing an image onto the canvas at a specific position. * * @param {Image} image - An element to draw into the context. The specification permits any canvas * image source (Image). * @param {f64} dx - The x-axis coordinate in the destination canvas at which to place the top-left * corner of the source image. * @param {f64} dy - The y-axis coordinate in the destination canvas at which to place the top-left * corner of the source image. */ public drawImage(image: Image | null, dx: f64, dy: f64): void { if (image == null || !isFinite(dx + dy) || !image.loaded) return; this._updateFilter(); this._updateGlobalAlpha(); this._updateGlobalCompositeOperation(); this._updateImageSmoothingEnabled(); this._updateImageSmoothingQuality(); this._updateShadowBlur(); this._updateShadowColor(); this._updateShadowOffsetX(); this._updateShadowOffsetY(); this._updateTransform(); this._writeNine( CanvasInstruction.DrawImage, <f64>getImageID(image), 0.0, 0.0, <f64>image.width, <f64>image.height, dx, dy, <f64>image.width, <f64>image.height, ); } /** * The CanvasRenderingContext2D.drawImageSize() method of the Canvas 2D API provides a simple * method for drawing an image onto the canvas at a specific position. * * @param {Image} image - An element to draw into the context. The specification permits any canvas * image source (Image). * @param {f64} dx - The x-axis coordinate in the destination canvas at which to place the top-left * corner of the source image. * @param {f64} dy - The y-axis coordinate in the destination canvas at which to place the top-left * corner of the source image. * @param {f64} dWidth - The width to draw the image in the destination canvas. This allows scaling * of the drawn image. If not specified, the image is not scaled in width when drawn. * @param {f64} dHeight - The height to draw the image in the destination canvas. This allows scaling * of the drawn image. If not specified, the image is not scaled in height when drawn. */ public drawImageSize(image: Image | null, dx: f64, dy: f64, dWidth: f64, dHeight: f64): void { if (image == null || !isFinite(dx + dy + dWidth + dHeight) || !image.loaded) return; this._updateFilter(); this._updateGlobalAlpha(); this._updateGlobalCompositeOperation(); this._updateImageSmoothingEnabled(); this._updateImageSmoothingQuality(); this._updateShadowBlur(); this._updateShadowColor(); this._updateShadowOffsetX(); this._updateShadowOffsetY(); this._updateTransform(); this._writeNine( CanvasInstruction.DrawImage, <f64>getImageID(image), 0.0, 0.0, <f64>image.width, <f64>image.height, dx, dy, dWidth, dHeight, ); } /** * The CanvasRenderingContext2D.drawImageSource() method of the Canvas 2D API provides a simple * method for drawing an image onto the canvas at a specific position. * * @param {Image} image - An element to draw into the context. The specification permits any canvas * image source (Image). * @param {f64} sx - The x-axis coordinate of the top left corner of the sub-rectangle of the source * image to draw into the destination context. * @param {f64} sy - The y-axis coordinate of the top left corner of the sub-rectangle of the source * image to draw into the destination context. * @param {f64} sWidth - The width of the sub-rectangle of the source image to draw into the * destination context. If not specified, the entire rectangle from the coordinates specified by sx * and sy to the bottom-right corner of the image is used. * @param {f64} sHeight - The height of the sub-rectangle of the source image to draw into the * destination context. * @param {f64} dx - The x-axis coordinate in the destination canvas at which to place the top-left * corner of the source image. * @param {f64} dy - The y-axis coordinate in the destination canvas at which to place the top-left * corner of the source image. * @param {f64} dWidth - The width to draw the image in the destination canvas. This allows scaling * of the drawn image. If not specified, the image is not scaled in width when drawn. * @param {f64} dHeight - The height to draw the image in the destination canvas. This allows scaling * of the drawn image. If not specified, the image is not scaled in height when drawn. */ public drawImageSource(image: Image | null, sx: f64, sy: f64, sWidth: f64, sHeight: f64, dx: f64, dy: f64, dWidth: f64, dHeight: f64): void { if (image == null || !isFinite(sx + sy + sWidth + sHeight + dx + dy + dWidth + dHeight) || !image.loaded) return; this._updateFilter(); this._updateGlobalAlpha(); this._updateGlobalCompositeOperation(); this._updateImageSmoothingEnabled(); this._updateImageSmoothingQuality(); this._updateShadowBlur(); this._updateShadowColor(); this._updateShadowOffsetX(); this._updateShadowOffsetY(); this._updateTransform(); this._writeNine( CanvasInstruction.DrawImage, <f64>getImageID(image), sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight, ); } //#endregion DRAWIMAGE //#region ELLIPSE /** * The CanvasRenderingContext2D.ellipse() method of the Canvas 2D API adds an elliptical arc to the current sub-path. * * @param {f64} x - The x-axis (horizontal) coordinate of the ellipse's center. * @param {f64} y - The y-axis (vertical) coordinate of the ellipse's center. * @param {f64} radiusX - The ellipse's major-axis radius. Must be non-negative. * @param {f64} radiusY - The ellipse's minor-axis radius. Must be non-negative. * @param {f64} rotation - The rotation of the ellipse, expressed in radians. * @param {f64} startAngle - The angle at which the ellipse starts, measured clockwise from the positive x-axis * and expressed in radians. * @param {f64} endAngle - The angle at which the ellipse ends, measured clockwise from the positive x-axis and * expressed in radians. * @param {bool} anticlockwise - An optional Boolean which, if true, draws the ellipse anticlockwise * (counter-clockwise). The default value is false (clockwise). */ public ellipse(x: f64, y: f64, radiusX: f64, radiusY: f64, rotation: f64, startAngle: f64, endAngle: f64, anticlockwise: bool = false): void { if (!isFinite(x + y + radiusX + radiusY + rotation + startAngle + endAngle) || radiusX < 0 || radiusY < 0) return; this._writePath( CanvasInstruction.Ellipse, true, 8, x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise ? 1.0 : 0.0, ); } //#endregion ELLIPSE //#region FILL /** * The CanvasRenderingContext2D.fill() method of the Canvas 2D API fills the current or given path * with the current fillStyle. * * @param {FillRule} fillRule - The algorithm by which to determine if a point is inside or * outside the filling region. * * Possible values: * - `FillRule.nonzero`: The non-zero winding rule. Default rule. * - `FillRule.evenodd`: The even-odd winding rule. */ public fill(fillRule: FillRule = FillRule.nonzero): void { /** * If there are no items on the path, there is no reason to fill. Index 1 means the path buffer * is pointing to a single `beginPath()` operation and it does not matter if fill is called at * this point. */ if (this._path == this._pathStart.increment()) return; this._updateFillStyle(); this._updateFilter(); this._updateGlobalAlpha(); this._updateGlobalCompositeOperation(); this._updateImageSmoothingEnabled(); this._updateImageSmoothingQuality(); /** * This function must be called *before* _updateTransform(), because both the path operations and the * fill operations affect the transform. Each pathing operation has it's own transform, and the * transform value when the fill operation occurs might be different. */ this._updatePath(); this._updateShadowBlur(); this._updateShadowColor(); this._updateShadowOffsetX(); this._updateShadowOffsetY(); this._updateTransform(); super._writeOne(CanvasInstruction.Fill, <f64>fillRule); } //#endregion FILL //#region FILLRECT /** * The CanvasRenderingContext2D.fillRect() method of the Canvas 2D API draws a rectangle that is * filled according to the current fillStyle. This method draws directly to the canvas without * modifying the current path, so any subsequent fill() or stroke() calls will have no effect on * it. * * @param x - The x-axis coordinate of the rectangle's starting point. * @param y - The y-axis coordinate of the rectangle's starting point. * @param width - The rectangle's width. Positive values are to the right, and negative to the * left. * @param height - The rectangle's height. Positive values are down, and negative are up. */ public fillRect(x: f64, y: f64, width: f64, height: f64): void { if (!isFinite(x + y + width + height)) return; this._updateFillStyle(); this._updateFilter(); this._updateGlobalAlpha(); this._updateGlobalCompositeOperation(); this._updateImageSmoothingEnabled(); this._updateImageSmoothingQuality(); this._updateShadowBlur(); this._updateShadowColor(); this._updateShadowOffsetX(); this._updateShadowOffsetY(); this._updateTransform(); super._writeFour(CanvasInstruction.FillRect, x, y, width, height); } //#endregion FILLRECT //#region FILLTEXT /** * The CanvasRenderingContext2D method fillText(), part of the Canvas 2D API, draws a text string * at the specified coordinates, filling the string's characters with the current fillStyle. An * optional parameter allows specifying a maximum width for the rendered text, which the user * agent will achieve by condensing the text or by using a lower font size. This method draws * directly to the canvas without modifying the current path, so any subsequent fill() or stroke() * calls will have no effect on it. The text is rendered using the font and text layout * configuration as defined by the font, textAlign, textBaseline, and direction properties. * * The fillText function can accept an optional maxWidth property. Use the fillTextWidth function * to enable the use of that parameter. * * @param text - A DOMString specifying the text string to render into the context. The text is * rendered using the settings specified by font, textAlign, textBaseline, and direction. * @param x - The x-axis coordinate of the point at which to begin drawing the text, in pixels. * @param y - The y-axis coordinate of the point at which to begin drawing the text, in pixels. */ public fillText(text: string, x: f64, y: f64): void { if (!isFinite(x + y) || text == null || text.length == 0) return; this._updateDirection(); this._updateFillStyle(); this._updateFilter(); this._updateFont(); this._updateGlobalAlpha(); this._updateGlobalCompositeOperation(); this._updateImageSmoothingEnabled(); this._updateImageSmoothingQuality(); this._updateShadowBlur(); this._updateShadowColor(); this._updateShadowOffsetX(); this._updateShadowOffsetY(); this._updateTextAlign(); this._updateTextBaseline(); this._updateTransform(); super._retain(changetype<usize>(text)); super._writeThree(CanvasInstruction.FillText, <f64>changetype<usize>(text), x, y); } /** * The CanvasRenderingContext2D method fillText(), part of the Canvas 2D API, draws a text string * at the specified coordinates, filling the string's characters with the current fillStyle. An * optional parameter allows specifying a maximum width for the rendered text, which the user * agent will achieve by condensing the text or by using a lower font size. This method draws * directly to the canvas without modifying the current path, so any subsequent fill() or stroke() * calls will have no effect on it. The text is rendered using the font and text layout * configuration as defined by the font, textAlign, textBaseline, and direction properties. * * The fillText function can accept an optional maxWidth property. Use the fillTextWidth function * to enable the use of that parameter. * * @param text - A DOMString specifying the text string to render into the context. The text is * rendered using the settings specified by font, textAlign, textBaseline, and direction. * @param x - The x-axis coordinate of the point at which to begin drawing the text, in pixels. * @param y - The y-axis coordinate of the point at which to begin drawing the text, in pixels. * @param maxWidth - The maximum number of pixels wide the text may be once rendered. If not * specified, there is no limit to the width of the text. However, if this value is provided, the * user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. */ public fillTextWidth(text: string, x: f64, y: f64, maxWidth: f64): void { if (!isFinite(x + y + maxWidth) || text == null || text.length == 0 || maxWidth < 0) return; this._updateDirection(); this._updateFillStyle(); this._updateFilter(); this._updateFont(); this._updateGlobalAlpha(); this._updateGlobalCompositeOperation(); this._updateImageSmoothingEnabled(); this._updateImageSmoothingQuality(); this._updateShadowBlur(); this._updateShadowColor(); this._updateShadowOffsetX(); this._updateShadowOffsetY(); this._updateTextAlign(); this._updateTextBaseline(); this._updateTransform(); super._retain(changetype<usize>(text)); super._writeFour(CanvasInstruction.FillTextWidth, <f64>changetype<usize>(text), x, y, maxWidth); } //#endregion FILLTEXT //#region ISPOINTINPATH /** * The CanvasRenderingContext2D.isPointInPath() method of the Canvas 2D API reports whether or not * the specified point is contained in the current path. It forces a commit to flush all the * current instructions to the buffer, updates the path, and then performs a pointInPath function * call on the canvas. * * @param {f64} x - The x-axis coordinate of the point to check. * @param {f64} y - The y-axis coordinate of the point to check. * @param {FillRule} fillRule - The algorithm by which to determine if a point is inside or * outside the path. * * Possible values: * - `FillRule.nonzero`: The non-zero winding rule. Default rule. * - `FillRule.evenodd`: The even-odd winding rule. */ public isPointInPath(x: f64, y: f64, fillRule: FillRule = FillRule.nonzero): bool { if (!isFinite(x + y)) return false; this._updatePath(); this.commit(); return isPointInPath(this.id, x, y, fillRule); } //#endregion ISPOINTINPATH //#region ISPOINTINSTROKE /** * The CanvasRenderingContext2D.isPointInStroke() method of the Canvas 2D API reports whether or * not the specified point is inside the area contained by the stroking of a path. It forces a * commit to flush all the current instructions to the buffer, updates the path, and then performs * a pointInPath function call on the canvas. * * @param {f64} x - The x-axis coordinate of the point to check. * @param {f64} y - The y-axis coordinate of the point to check. */ public isPointInStroke(x: f64, y: f64): bool { if (!isFinite(x + y)) return false; this._updatePath(); this.commit(); return isPointInStroke(this.id, x, y); } //#endregion ISPOINTINSTROKE //#region LINETO /** * The CanvasRenderingContext2D method lineTo(), part of the Canvas 2D API, adds a straight line * to the current sub-path by connecting the sub-path's last point to the specified (x, y) * coordinates. Like other methods that modify the current path, this method does not directly * render anything. To draw the path onto a canvas, you can use the fill() or stroke() methods. * * @param {f64} x - The x-axis coordinate of the line's end point. * @param {f64} y - The y-axis coordinate of the line's end point. */ public lineTo(x: f64, y: f64): void { if (!isFinite(x + y)) return; this._writePath(CanvasInstruction.LineTo, true, 2, x, y); } //#endregion LINETO //#region MEASURETEXT /** * The CanvasRenderingContext2D.measureText() method returns a TextMetrics object that contains * information about the measured text (such as its width, for example). The as2d implementation * only returns the resulting width property value. * * @param {string} text - The text string to measure. */ public measureText(text: string): f64 { this._updateFont(); this.commit(); return measureText(this.id, text); } //#endregion MEASURETEXT //#region MOVETO /** * The CanvasRenderingContext2D.moveTo() method of the Canvas 2D API begins a new sub-path at the * point specified by the given (x, y) coordinates. * * @param {f64} x - The x-axis (horizontal) coordinate of the point. * @param {f64} y - The y-axis (vertical) coordinate of the point. */ public moveTo(x: f64, y: f64): void { if (!isFinite(x + y)) return; this._writePath(CanvasInstruction.MoveTo, true, 2, x, y); } //#endregion MOVETO //#region QUADRATICCURVETO /** * The CanvasRenderingContext2D.quadraticCurveTo() method of the Canvas 2D API adds a quadratic * Bézier curve to the current sub-path. It requires two points: the first one is a control point * and the second one is the end point. The starting point is the latest point in the current * path, which can be changed using moveTo() before creating the quadratic Bézier curve. * * @param cpx - The x-axis coordinate of the control point. * @param cpy - The y-axis coordinate of the control point. * @param x - The x-axis coordinate of the end point. * @param y - The y-axis coordinate of the end point. */ public quadraticCurveTo(cpx: f64, cpy: f64, x: f64, y: f64): void { if (!isFinite(cpx + cpy + x + y)) return; this._writePath(CanvasInstruction.QuadraticCurveTo, true, 4, cpx, cpy, x, y); } //#endregion QUADRATICCURVETO //#region RECT /** * The CanvasRenderingContext2D.rect() method of the Canvas 2D API adds a rectangle to the current * path. Like other methods that modify the current path, this method does not directly render * anything. To draw the rectangle onto a canvas, you can use the fill() or stroke() methods. * * @param {f64} x - The x-axis coordinate of the rectangle's starting point. * @param {f64} y - The y-axis coordinate of the rectangle's starting point. * @param {f64} width - The rectangle's width. Positive values are to the right, and negative to * the left. * @param {f64} height - The rectangle's height. Positive values are down, and negative are up. */ public rect(x: f64, y: f64, width: f64, height: f64): void { if (!isFinite(x + y + width + height)) return; this._writePath(CanvasInstruction.Rect, true, 4, x, y, width, height); } //#endregion RECT //#region RESETTRANSFORM /** * The CanvasRenderingContext2D.resetTransform() method of the Canvas 2D API resets the current * transform to the identity matrix. */ public resetTransform(): void { this.setTransform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); } //#endregion RESETTRANSFORM //#region ROTATE /** * The CanvasRenderingContext2D.rotate() method of the Canvas 2D API adds a rotation to the * transformation matrix. * * @param {f64} angle - The rotation angle, clockwise in radians. You can use * `degree * Math.PI / 180` if you want to calculate from a degree value. */ public rotate(angle: f64): void { if (!isFinite(angle)) return; NativeMath.sincos(angle); var cos: f64 = NativeMath.sincos_cos; var sin: f64 = NativeMath.sincos_sin; if (ASC_FEATURE_SIMD) { let stack = this._stack.dereference(); let cossplat = v128.splat<f64>(cos); let sinsplat = v128.splat<f64>(sin); let ab = v128.load(stack, offsetof<CanvasStack>("a")); let cb = v128.load(stack, offsetof<CanvasStack>("c")); v128.store(stack, v128.add<f64>( v128.mul<f64>(ab, cossplat), v128.mul<f64>(cb, sinsplat), ), offsetof<CanvasStack>("a"), ); v128.store(stack, v128.sub<f64>( v128.mul<f64>(cb, cossplat), v128.mul<f64>(ab, sinsplat), ), offsetof<CanvasStack>("c"), ); } else { var stack = this._stack.reference(); var a = stack.a; var b = stack.b; var c = stack.c; var d = stack.d; stack.a = a * cos + c * sin; stack.b = b * cos + d * sin; stack.c = c * cos - a * sin; stack.d = d * cos - b * sin; } } //#endregion ROTATE //#region SCALE /** * The CanvasRenderingContext2D.scale() method of the Canvas 2D API adds a scaling transformation * to the canvas units horizontally and/or vertically. By default, one unit on the canvas is * exactly one pixel. A scaling transformation modifies this behavior. For instance, a scaling * factor of 0.5 results in a unit size of 0.5 pixels; shapes are thus drawn at half the normal * size. Similarly, a scaling factor of 2.0 increases the unit size so that one unit becomes two * pixels; shapes are thus drawn at twice the normal size. * * @param {f64} x - Scaling factor in the horizontal direction. A negative value flips pixels * across the vertical axis. A value of 1 results in no horizontal scaling. * @param {f64} y - Scaling factor in the vertical direction. A negative value flips pixels across * the horizontal axis. A value of 1 results in no vertical scaling. */ public scale(x: f64, y: f64): void { if (!isFinite(x + y)) return; if (ASC_FEATURE_SIMD) { let stack = this._stack.dereference(); v128.store(stack, v128.mul<f64>( v128.load(stack, offsetof<CanvasStack>("a")), v128.splat<f64>(x), ), offsetof<CanvasStack>("a"), ); v128.store(stack, v128.mul<f64>( v128.load(stack, offsetof<CanvasStack>("c")), v128.splat<f64>(y), ), offsetof<CanvasStack>("c"), ); } else { let stack = this._stack.reference(); stack.a *= x; stack.b *= x; stack.c *= y; stack.d *= y; } } //#endregion SCALE //#region SETTRANSFORM /** * The CanvasRenderingContext2D.setTransform() method of the Canvas 2D API resets (overrides) the * current transformation to the identity matrix, and then invokes a transformation described by * the arguments of this method. This lets you scale, rotate, translate (move), and skew the * context. * * @param {f64} a - Horizontal scaling. A value of 1 results in no scaling. * @param {f64} b - Vertical skewing. * @param {f64} c - Horizontal skewing. * @param {f64} d - Vertical scaling. A value of 1 results in no scaling. * @param {f64} e - Horizontal translation (moving). * @param {f64} f - Vertical translation (moving). */ public setTransform(a: f64, b: f64, c: f64, d: f64, e: f64, f: f64): void { if (!isFinite(a + b + c + d + e + f)) return ; let stack = this._stack.reference(); stack.a = a; stack.b = b; stack.c = c; stack.d = d; stack.e = e; stack.f = f; } //#endregion SETTRANSFORM //#region STROKE /** * The CanvasRenderingContext2D.stroke() method of the Canvas 2D API strokes (outlines) the * current or given path with the current stroke style. Strokes are aligned to the center of a * path; in other words, half of the stroke is drawn on the inner side, and half on the outer * side. The stroke is drawn using the non-zero winding rule, which means that path intersections * will still get filled. */ public stroke(): void { /** * If there are no items on the path, there is no reason to fill. Index 1 means the path buffer * is pointing to a single `beginPath()` operation and it does not matter if fill is called at * this point. */ if (this._path == this._pathStart.increment()) return; /** * If the lineWidth is zero, there is no line and it does not matter if ctx.stroke() is called. */ if (this._stack.reference().lineWidth <= 0.0) return; this._updateFilter(); this._updateGlobalAlpha(); this._updateGlobalCompositeOperation(); this._updateImageSmoothingEnabled(); this._updateImageSmoothingQuality(); this._updateLineCap(); this._updateLineDash(); this._updateLineDashOffset(); this._updateLineJoin(); this._updateLineWidth(); this._updateMiterLimit(); this._updatePath(); this._updateShadowBlur(); this._updateShadowColor(); this._updateShadowOffsetX(); this._updateShadowOffsetY(); this._updateStrokeStyle(); this._updateTransform(); super._writeZero(CanvasInstruction.Stroke); } //#endregion STROKE //#region STROKERECT /** * The CanvasRenderingContext2D.strokeRect() method of the Canvas 2D API draws a rectangle that is * stroked (outlined) according to the current strokeStyle and other context settings. This method * draws directly to the canvas without modifying the current path, so any subsequent fill() or * stroke() calls will have no effect on it. * * @param {f64} x - The x-axis coordinate of the rectangle's starting point. * @param {f64} y - The y-axis coordinate of the rectangle's starting point. * @param {f64} width - The rectangle's width. Positive values are to the right, and negative to * the left. * @param {f64} height - The rectangle's height. Positive values are down, and negative are up. */ public strokeRect(x: f64, y: f64, width: f64, height: f64): void { /** * If the lineWidth is zero, there is no line and it does not matter if ctx.stroke() is called. */ if (this._stack.reference().lineWidth <= 0.0) return; this._updateFilter(); this._updateGlobalAlpha(); this._updateGlobalCompositeOperation(); this._updateImageSmoothingEnabled(); this._updateImageSmoothingQuality(); this._updateLineCap(); this._updateLineDash(); this._updateLineDashOffset(); this._updateLineJoin(); this._updateLineWidth(); this._updateMiterLimit(); this._updateShadowBlur(); this._updateShadowColor(); this._updateShadowOffsetX(); this._updateShadowOffsetY(); this._updateStrokeStyle(); this._updateTransform(); super._writeFour(CanvasInstruction.StrokeRect, x, y, width, height); } //#endregion STROKERECT //#region STROKETEXT /** * The CanvasRenderingContext2D method strokeText(), part of the Canvas 2D API, strokes — that is, * draws the outlines of — the characters of a text string at the specified coordinates. An * optional parameter allows specifying a maximum width for the rendered text, which the user * agent will achieve by condensing the text or by using a lower font size. This method draws * directly to the canvas without modifying the current path, so any subsequent fill() or stroke() * calls will have no effect on it. To use the maxWidth parameter, use the strokeTextWidth * function. * * @param {string} text - A DOMString specifying the text string to render into the context. The * text is rendered using the settings specified by font, textAlign, textBaseline, and direction. * @param {f64} x - The x-axis coordinate of the point at which to begin drawing the text. * @param {f64} y - The y-axis coordinate of the point at which to begin drawing the text. */ public strokeText(text: string, x: f64, y: f64): void { if (!isFinite(x + y) || text == null || text.length == 0) return; this._updateDirection(); this._updateFilter(); this._updateFont(); this._updateGlobalAlpha(); this._updateGlobalCompositeOperation(); this._updateImageSmoothingEnabled(); this._updateImageSmoothingQuality(); this._updateLineCap(); this._updateLineDash(); this._updateLineDashOffset(); this._updateLineJoin(); this._updateLineWidth(); this._updateMiterLimit(); this._updateShadowBlur(); this._updateShadowColor(); this._updateShadowOffsetX(); this._updateShadowOffsetY(); this._updateStrokeStyle(); this._updateTextAlign(); this._updateTextBaseline(); this._updateTransform(); super._retain(changetype<usize>(text)); super._writeThree(CanvasInstruction.StrokeText, <f64>changetype<usize>(text), x, y) } /** * The CanvasRenderingContext2D method strokeTextWidth(), part of the Canvas 2D API, strokes — * that is, draws the outlines of — the characters of a text string at the specified coordinates. * An optional parameter allows specifying a maximum width for the rendered text, which the user * agent will achieve by condensing the text or by using a lower font size. This method draws * directly to the canvas without modifying the current path, so any subsequent fill() or stroke() * calls will have no effect on it. To use the maxWidth parameter, use the strokeTextWidth * function. * * @param {string} text - A DOMString specifying the text string to render into the context. The * text is rendered using the settings specified by font, textAlign, textBaseline, and direction. * @param {f64} x - The x-axis coordinate of the point at which to begin drawing the text. * @param {f64} y - The y-axis coordinate of the point at which to begin drawing the text. * @param {f64} maxWidth - The maximum width the text may be once rendered. If not specified, * there is no limit to the width of the text. However, if this value is provided, the user agent * will adjust the kerning, select a more horizontally condensed font (if one is available or can * be generated without loss of quality), or scale down to a smaller font size in order to fit the * text in the specified width. */ public strokeTextWidth(text: string, x: f64, y: f64, maxWidth: f64): void { if (!isFinite(x + y + maxWidth) || text == null || text.length == 0 || maxWidth < 0) return; this._updateDirection(); this._updateFilter(); this._updateFont(); this._updateGlobalAlpha(); this._updateGlobalCompositeOperation(); this._updateImageSmoothingEnabled(); this._updateImageSmoothingQuality(); this._updateLineCap(); this._updateLineDash(); this._updateLineDashOffset(); this._updateLineJoin(); this._updateLineWidth(); this._updateMiterLimit(); this._updateShadowBlur(); this._updateShadowColor(); this._updateShadowOffsetX(); this._updateShadowOffsetY(); this._updateStrokeStyle(); this._updateTextAlign(); this._updateTextBaseline(); this._updateTransform(); super._retain(changetype<usize>(text)); super._writeFour(CanvasInstruction.StrokeTextWidth, <f64>changetype<usize>(text), x, y, maxWidth); } //#endregion STROKETEXT //#region TRANSFORM /** * The CanvasRenderingContext2D.transform() method of the Canvas 2D API multiplies the current * transformation with the matrix described by the arguments of this method. This lets you scale, * rotate, translate (move), and skew the context. * * @param {f64} a - Horizontal scaling. A value of 1 results in no scaling. * @param {f64} b - Vertical skewing. * @param {f64} c - Horizontal skewing. * @param {f64} d - Vertical scaling. A value of 1 results in no scaling. * @param {f64} e - Horizontal translation (moving). * @param {f64} f - Vertical translation (moving). */ public transform(a: f64, b: f64, c: f64, d: f64, e: f64, f: f64): void { if (!isFinite(a + b + c + d + e + f)) return; if (ASC_FEATURE_SIMD) { let stack = this._stack.dereference(); let ab = v128.load(stack, offsetof<CanvasStack>("a")); let cd = v128.load(stack, offsetof<CanvasStack>("c")); let ef = v128.load(stack, offsetof<CanvasStack>("e")); v128.store( stack, v128.add<f64>( v128.mul<f64>(ab, v128.splat<f64>(a)), v128.mul<f64>(cd, v128.splat<f64>(b)), ), offsetof<CanvasStack>("a"), ); v128.store( stack, v128.add<f64>( v128.mul<f64>(ab, v128.splat<f64>(c)), v128.mul<f64>(cd, v128.splat<f64>(d)), ), offsetof<CanvasStack>("c"), ); v128.store( stack, v128.add<f64>( v128.add<f64>( v128.mul<f64>(ab, v128.splat<f64>(e)), v128.mul<f64>(cd, v128.splat<f64>(f)), ), ef, ), offsetof<CanvasStack>("e"), ); } else { let stack = this._stack.reference(); var sa = stack.a; var sb = stack.b; var sc = stack.c; var sd = stack.d; var se = stack.e; var sf = stack.f; stack.a = sa * a + sc * b; stack.b = sb * a + sd * b; stack.c = sa * c + sc * d; stack.d = sb * c + sd * d; stack.e = sa * e + sc * f + se; stack.f = sb * e + sd * f + sf; } } //#endregion TRANSFORM //#region TRANSLATE /** * The CanvasRenderingContext2D.translate() method of the Canvas 2D API adds a translation * transformation to the current matrix. * @param {f64} x - Distance to move in the horizontal direction. Positive values are to the * right, and negative to the left. * @param {f64} y - Distance to move in the vertical direction. Positive values are down, and * negative are up. */ public translate(x: f64, y: f64): void { if (!isFinite(x + y)) return; if (ASC_FEATURE_SIMD) { let stack = this._stack.dereference(); v128.store( stack, v128.add<f64>( v128.mul<f64>( v128.load(stack, offsetof<CanvasStack>("a")), v128.splat<f64>(x), ), v128.mul<f64>( v128.load(stack, offsetof<CanvasStack>("c")), v128.splat<f64>(y), ), ), offsetof<CanvasStack>("e"), ); } else { let stack = this._stack.reference(); stack.e += stack.a * x + stack.c * y; stack.f += stack.b * x + stack.d * y; } } //#endregion TRANSLATE public commit(): void { super._writeZero(CanvasInstruction.Commit); render(this.id, changetype<usize>(this._buffer)); super._resetBuffer(); } }
the_stack
declare module "simpl-schema" { // Type definitions for simpl-schema type Integer = RegExp; type SchemaType = | String | Number | Integer | Boolean | Object | ArrayLike<any> | SchemaDefinition<any> | Date | SimpleSchema | SimpleSchemaGroup; type SimpleSchemaGroup = { definitions: ArrayLike<{ type: SchemaType }> }; interface CleanOption { filter?: boolean; autoConvert?: boolean; removeEmptyStrings?: boolean; trimStrings?: boolean; getAutoValues?: boolean; isModifier?: boolean; extendAutoValueContext?: boolean; } export type AutoValueFunctionSelf<T> = { key: string; closestSubschemaFieldName: string | null; isSet: boolean; unset: () => void; value: T; // | Mongo.Modifier<T>; operator: string; field( otherField: string ): { isSet: boolean; value: any; operator: string; }; siblingField( otherField: string ): { isSet: boolean; value: any; operator: string; }; parentField( otherField: string ): { isSet: boolean; value: any; operator: string; }; }; type ValidationError = { name: string; type: string; value: any; }; type AutoValueFunction<T> = (this: AutoValueFunctionSelf<T>) => T | undefined; interface ValidationFunctionSelf<T> { value: T; key: string; genericKey: string; definition: SchemaDefinition<T>; isSet: boolean; operator: any; validationContext: ValidationContext; field: (fieldName: string) => any; siblingField: (fieldName: string) => any; addValidationErrors: (errors: ValidationError[]) => {}; } type ValidationFunction = ( this: ValidationFunctionSelf<any> ) => string | undefined; export interface SchemaDefinition<T> { type: SchemaType; label?: string | Function; optional?: boolean | Function; min?: number | boolean | Date | Function; max?: number | boolean | Date | Function; minCount?: number | Function; maxCount?: number | Function; allowedValues?: any[] | Function; decimal?: boolean; exclusiveMax?: boolean; exclusiveMin?: boolean; regEx?: RegExp | RegExp[]; custom?: ValidationFunction; blackbox?: boolean; autoValue?: AutoValueFunction<T>; defaultValue?: any; trim?: boolean; // allow custom extensions [key: string]: any; } export interface EvaluatedSchemaDefinition { type: ArrayLike<{ type: SchemaType }>; label?: string; optional?: boolean; min?: number | boolean | Date; max?: number | boolean | Date; minCount?: number; maxCount?: number; allowedValues?: any[]; decimal?: boolean; exclusiveMax?: boolean; exclusiveMin?: boolean; regEx?: RegExp | RegExp[]; blackbox?: boolean; defaultValue?: any; trim?: boolean; // allow custom extensions [key: string]: any; } interface ValidationOption { modifier?: boolean; upsert?: boolean; clean?: boolean; filter?: boolean; upsertextendedCustomContext?: boolean; extendedCustomContext: any; } interface SimpleSchemaValidationContext { validate(obj: any, options?: ValidationOption): boolean; validateOne(doc: any, keyName: string, options?: ValidationOption): boolean; resetValidation(): void; isValid(): boolean; invalidKeys(): { name: string; type: string; value?: any }[]; addInvalidKeys(errors: ValidationError[]): void; keyIsInvalid(name: any): boolean; keyErrorMessage(name: any): string; getErrorObject(): any; validationErrors(): Array<{ type?: string; name?: string }>; } class ValidationContext { constructor(ss: any); addValidationErrors(errors: ValidationError[]): void; clean(...args: any[]): any; getErrorForKey(key: any, ...args: any[]): any; isValid(): any; keyErrorMessage(key: any, ...args: any[]): any; keyIsInvalid(key: any, ...args: any[]): any; reset(): void; setValidationErrors(errors: ValidationError): void; validate(obj: any, ...args: any[]): any; validationErrors(): any; } interface MongoObjectStatic { forEachNode(func: Function, options?: { endPointsOnly: boolean }): void; getValueForPosition(position: string): any; setValueForPosition(position: string, value: any): void; removeValueForPosition(position: string): void; getKeyForPosition(position: string): any; getGenericKeyForPosition(position: string): any; getInfoForKey(key: string): any; getPositionForKey(key: string): string; getPositionsForGenericKey(key: string): string[]; getValueForKey(key: string): any; addKey(key: string, val: any, op: string): any; removeGenericKeys(keys: string[]): void; removeGenericKey(key: string): void; removeKey(key: string): void; removeKeys(keys: string[]): void; filterGenericKeys(test: Function): void; setValueForKey(key: string, val: any): void; setValueForGenericKey(key: string, val: any): void; getObject(): any; getFlatObject(options?: { keepArrays?: boolean }): any; affectsKey(key: string): any; affectsGenericKey(key: string): any; affectsGenericKeyImplicit(key: string): any; } interface MongoObject { expandKey(val: any, key: string, obj: any): void; } class SimpleSchema { static Integer: Integer; static RegEx: { Email: RegExp; EmailWithTLD: RegExp; Domain: RegExp; WeakDomain: RegExp; IP: RegExp; IPv4: RegExp; IPv6: RegExp; Url: RegExp; Id: RegExp; ZipCode: RegExp; Phone: RegExp; }; debug: boolean; // TODO: improve this typing _schema: any; constructor( schema: { [key: string]: SchemaDefinition<any> | SchemaType } | any[], options?: | any | { humanizeAutoLabels?: boolean; tracker?: any; check?: any } ); /** * Returns whether the obj is a SimpleSchema object. * @param {Object} [obj] An object to test * @returns {Boolean} True if the given object appears to be a SimpleSchema instance */ static isSimpleSchema(obj: any): boolean; static oneOf(...schemas: SchemaType[]): SchemaType; // If you need to allow properties other than those listed above, call this from your app or package static extendOptions(allowedOptionFields: string[]): void; static setDefaultMessages(messages: { messages: { [key: string]: { [key: string]: string } }; }): void; namedContext(name?: string): SimpleSchemaValidationContext; addDocValidator(validator: (doc: any) => ValidationError[]): any; /** * @method SimpleSchema#pick * @param {[fields]} The list of fields to pick to instantiate the subschema * @returns {SimpleSchema} The subschema */ pick(...fields: string[]): SimpleSchema; /** * @method SimpleSchema#omit * @param {[fields]} The list of fields to omit to instantiate the subschema * @returns {SimpleSchema} The subschema */ omit(...fields: string[]): SimpleSchema; /** * Extends this schema with another schema, key by key. * * @param {SimpleSchema|Object} schema * @returns The SimpleSchema instance (chainable) */ extend( schema: | Partial<SchemaDefinition<any>> | SimpleSchema | { [key: string]: Partial<SchemaDefinition<any>> } ): SimpleSchema; clean(doc: any, options?: CleanOption): any; /** * @param {String} [key] One specific or generic key for which to get the schema. * @returns {Object} The entire schema object or just the definition for one key. * * Note that this returns the raw, unevaluated definition object. Use `getDefinition` * if you want the evaluated definition, where any properties that are functions * have been run to produce a result. */ schema<T>( key?: string ): SchemaDefinition<T> | { [key: string]: SchemaDefinition<T> }; /** * @returns {Object} The entire schema object with subschemas merged. This is the * equivalent of what schema() returned in SimpleSchema < 2.0 * * Note that this returns the raw, unevaluated definition object. Use `getDefinition` * if you want the evaluated definition, where any properties that are functions * have been run to produce a result. */ mergedSchema(): { [key: string]: SchemaDefinition<any> }; /** * Returns the evaluated definition for one key in the schema * * @param {String} key Generic or specific schema key * @param {Array(String)} [propList] Array of schema properties you need; performance optimization * @param {Object} [functionContext] The context to use when evaluating schema options that are functions * @returns {Object} The schema definition for the requested key */ getDefinition( key: string, propList?: ArrayLike<string>, functionContext?: any ): EvaluatedSchemaDefinition; /** * Returns a string identifying the best guess data type for a key. For keys * that allow multiple types, the first type is used. This can be useful for * building forms. * * @param {String} key Generic or specific schema key * @returns {String} A type string. One of: * string, number, boolean, date, object, stringArray, numberArray, booleanArray, * dateArray, objectArray */ getQuickTypeForKey( key: string ): | "string" | "number" | "boolean" | "date" | "object" | "stringArray" | "numberArray" | "booleanArray" | "dateArray" | "objectArray" | undefined; /** * Given a key that is an Object, returns a new SimpleSchema instance scoped to that object. * * @param {String} key Generic or specific schema key */ getObjectSchema(key: string): SimpleSchema; // Returns an array of all the autovalue functions, including those in subschemas all the // way down the schema tree autoValueFunctions(): AutoValueFunction<any>[]; // Returns an array of all the blackbox keys, including those in subschemas blackboxKeys(): ArrayLike<string>; // Check if the key is a nested dot-syntax key inside of a blackbox object keyIsInBlackBox(key: string): boolean; /** * Change schema labels on the fly, causing mySchema.label computation * to rerun. Useful when the user changes the language. * * @param {Object} labels A dictionary of all the new label values, by schema key. */ labels(labels: { [key: string]: string }): void; /** * Gets a field's label or all field labels reactively. * * @param {String} [key] The schema key, specific or generic. * Omit this argument to get a dictionary of all labels. * @returns {String} The label */ label(key: any): any; /** * Gets a field's property * * @param {String} [key] The schema key, specific or generic. * Omit this argument to get a dictionary of all labels. * @param {String} [prop] Name of the property to get. * * @returns {any} The property value */ get(key?: string, prop?: string): any; // shorthand for getting defaultValue defaultValue(key): any; messages(messages: any): void; // Returns a string message for the given error type and key. Passes through // to message-box pkg. messageForError(type: any, key: any, def: any, value: any): string; // Returns true if key is explicitly allowed by the schema or implied // by other explicitly allowed keys. // The key string should have $ in place of any numeric array positions. allowsKey(key: any): boolean; newContext(): ValidationContext; /** * Returns all the child keys for the object identified by the generic prefix, * or all the top level keys if no prefix is supplied. * * @param {String} [keyPrefix] The Object-type generic key for which to get child keys. Omit for * top-level Object-type keys * @returns {[[Type]]} [[Description]] */ objectKeys(keyPrefix?: any): any[]; /** * @param obj {Object|Object[]} Object or array of objects to validate. * @param [options] {Object} Same options object that ValidationContext#validate takes * * Throws an Error with name `ClientError` and `details` property containing the errors. */ validate(obj: any, options?: ValidationOption): void; /** * @param obj {Object} Object to validate. * @param [options] {Object} Same options object that ValidationContext#validate takes * * Returns a Promise that resolves with the errors */ validateAndReturnErrorsPromise( obj: any, options?: ValidationOption ): Promise<ArrayLike<Error>>; validator( options?: ValidationOption ): (args: { [key: string]: any }) => void; } export default SimpleSchema; }
the_stack
import * as vscode from "vscode"; /** * * Text and numeric constants used throughout leoInteg */ export class Constants { public static PUBLISHER: string = "boltex"; public static NAME: string = "leointeg"; public static CONFIG_NAME: string = "leoIntegration"; public static CONFIG_WORKBENCH_ENABLED_PREVIEW: string = "workbench.editor.enablePreview"; public static CONFIG_REFRESH_MATCH: string = "OnNodes"; // substring to distinguish 'on-hover' icon commands public static TREEVIEW_ID: string = Constants.CONFIG_NAME; public static TREEVIEW_EXPLORER_ID: string = Constants.CONFIG_NAME + "Explorer"; public static DOCUMENTS_ID: string = "leoDocuments"; public static DOCUMENTS_EXPLORER_ID: string = "leoDocumentsExplorer"; public static BUTTONS_ID: string = "leoButtons"; public static BUTTONS_EXPLORER_ID: string = "leoButtonsExplorer"; public static FIND_ID: string = "leoFindPanel"; public static FIND_EXPLORER_ID: string = "leoFindPanelExplorer"; public static VERSION_STATE_KEY: string = "leoIntegVersion"; public static FILE_EXTENSION: string = "leo"; public static JS_FILE_EXTENSION: string = "leojs"; public static URI_LEO_SCHEME: string = "leo"; public static URI_FILE_SCHEME: string = "file"; public static URI_SCHEME_HEADER: string = "leo:/"; public static FILE_OPEN_FILTER_MESSAGE: string = "Leo Files"; public static UNTITLED_FILE_NAME: string = "untitled"; public static RECENT_FILES_KEY: string = "leoRecentFiles"; public static LAST_FILES_KEY: string = "leoLastFiles"; public static DEFAULT_PYTHON: string = "python3"; public static WIN32_PYTHON: string = "py"; public static SERVER_NAME: string = "/leoserver.py"; public static SERVER_STARTED_TOKEN: string = "LeoBridge started"; public static TCPIP_DEFAULT_PROTOCOL: string = "ws://"; public static ERROR_PACKAGE_ID: number = 0; public static STARTING_PACKAGE_ID: number = 1; public static STATUSBAR_DEBOUNCE_DELAY: number = 60; public static DOCUMENTS_DEBOUNCE_DELAY: number = 80; public static BUTTONS_DEBOUNCE_DELAY: number = 80; public static REFRESH_ALL_DEBOUNCE_DELAY: number = 333; public static STATES_DEBOUNCE_DELAY: number = 100; public static BODY_STATES_DEBOUNCE_DELAY: number = 200; public static LOG_ALERT_COLOR: string = 'red'; /** * * Find panel controls ids */ public static FIND_INPUTS_IDS = { FIND_TEXT: "findText", REPLACE_TEXT: "replaceText", ENTIRE_OUTLINE: "entireOutline", NODE_ONLY: "nodeOnly", SUBOUTLINE_ONLY: "subOutlineOnly", IGNORE_CASE: "ignoreCase", MARK_CHANGES: "markChanges", MARK_FINDS: "markFinds", REG_EXP: "regExp", WHOLE_WORD: "wholeWord", SEARCH_BODY: "searchBody", SEARCH_HEADLINE: "searchHeadline" }; /** * * Strings used in the workbench interface panels (not for messages or dialogs) */ public static GUI = { ICON_LIGHT_DOCUMENT: "resources/light/document.svg", ICON_DARK_DOCUMENT: "resources/dark/document.svg", ICON_LIGHT_DOCUMENT_DIRTY: "resources/light/document-dirty.svg", ICON_DARK_DOCUMENT_DIRTY: "resources/dark/document-dirty.svg", ICON_LIGHT_BUTTON: "resources/light/button.svg", ICON_DARK_BUTTON: "resources/dark/button.svg", ICON_LIGHT_BUTTON_ADD: "resources/light/button-add.svg", ICON_DARK_BUTTON_ADD: "resources/dark/button-add.svg", ICON_LIGHT_PATH: "resources/light/box", ICON_DARK_PATH: "resources/dark/box", ICON_FILE_EXT: ".svg", STATUSBAR_INDICATOR: "$(keyboard) ", QUICK_OPEN_LEO_COMMANDS: ">leo: ", EXPLORER_TREEVIEW_PREFIX: "LEO ", TREEVIEW_TITLE: "OUTLINE", TREEVIEW_TITLE_NOT_CONNECTED: "NOT CONNECTED", TREEVIEW_TITLE_CONNECTED: "CONNECTED", TREEVIEW_TITLE_INTEGRATION: "INTEGRATION", BODY_TITLE: "LEO BODY", LOG_PANE_TITLE: "Leo Log Window", TERMINAL_PANE_TITLE: "LeoBridge Server", THEME_STATUSBAR: "statusBar.foreground" }; /** * * Basic user messages strings for messages and dialogs */ public static USER_MESSAGES = { SCRIPT_BUTTON: "from selected node", SCRIPT_BUTTON_TOOLTIP: "Creates a new button with the presently selected node.\n" + "For example, to run a script on any part of an outline:\n" + "\n" + "1. Select the node containing a script. e.g. \"g.es(p.h)\"\n" + "2. Press 'Script Button' to create a new button.\n" + "3. Select another node on which to run the script.\n" + "4. Press the *new* button.", SAVE_CHANGES: "Save changes to", BEFORE_CLOSING: "before closing?", CANCEL: "Cancel", OPEN_WITH_LEOINTEG: "Open this Leo file with LeoInteg?", OPEN_RECENT_FILE: "Open Recent Leo File", RIGHT_CLICK_TO_OPEN: "Right-click Leo files to open with LeoInteg", FILE_ALREADY_OPENED: "Leo file already opened", CHOOSE_OPENED_FILE: "Select an opened Leo File", FILE_NOT_OPENED: "No files opened.", STATUSBAR_TOOLTIP_ON: "Leo Key Bindings are in effect", // TODO : Add description of what happens if clicked STATUSBAR_TOOLTIP_OFF: "Leo Key Bindings off", // TODO : Add description of what happens if clicked PROMPT_EDIT_HEADLINE: "Edit Headline", PROMPT_INSERT_NODE: "Insert Node", DEFAULT_HEADLINE: "New Headline", TITLE_GOTO_GLOBAL_LINE: "Goto global line", PLACEHOLDER_GOTO_GLOBAL_LINE: "#", PROMPT_GOTO_GLOBAL_LINE: "Line number", TITLE_TAG_CHILDREN: "Tag Children", PLACEHOLDER_TAG_CHILDREN: "<tag>", PROMPT_TAG_CHILDREN: "Enter a tag name", TITLE_FIND_TAG: "Find Tag", PLACEHOLDER_CLONE_FIND_TAG: "<tag>", PROMPT_CLONE_FIND_TAG: "Enter a tag name", START_SERVER_ERROR: "Error - Cannot start server: ", CONNECT_FAILED: "Leo Server Connection Failed", CONNECT_ERROR: "Leo Server Connection Error: Incorrect id", CONNECTED: "Connected", ALREADY_CONNECTED: "Already connected", DISCONNECTED: "Disconnected", CLEARED_RECENT: "Cleared recent files list", CLOSE_ERROR: "Cannot close: No files opened.", LEO_PATH_MISSING: "Leo Editor Path Setting Missing", CANNOT_FIND_SERVER_SCRIPT: "Cannot find server script", YES: "Yes", NO: "No", YES_ALL: "Yes to all", NO_ALL: "No to all", MINIBUFFER_PROMPT: "Minibuffer Full Command", CHANGES_DETECTED: "Changes to external files were detected.", REFRESHED: " Nodes refreshed.", // with voluntary leading space IGNORED: " They were ignored.", // with voluntary leading space TOO_FAST: "leoInteg is busy! " // with voluntary trailing space }; /** * * Possible import file types */ public static IMPORT_FILE_TYPES: { [name: string]: string[]; } = { "All files": ["*"], "C/C++ files": ["c", "cpp", "h", "hpp"], "FreeMind files": ["mm.html"], "Java files": ["java"], "JavaScript files": ["js"], // "JSON files": ["json"], "Mindjet files": ["csv"], "MORE files": ["MORE"], "Lua files": ["lua"], "Pascal files": ["pas"], "Python files": ["py"], "Text files": ["txt"], }; /** * * Choices offered when about to lose current changes to a Leo Document */ public static ASK_SAVE_CHANGES_BUTTONS: vscode.MessageItem[] = [ { title: Constants.USER_MESSAGES.YES, isCloseAffordance: false }, { title: Constants.USER_MESSAGES.NO, isCloseAffordance: false }, { title: Constants.USER_MESSAGES.CANCEL, isCloseAffordance: true } ]; /** * * Strings used in 'at-button' panel display in LeoButtonNode */ public static BUTTON_STRINGS = { NULL_WIDGET: "nullButtonWidget", SCRIPT_BUTTON: "script-button", ADD_BUTTON: "leoButtonAdd", NORMAL_BUTTON: "leoButtonNode" }; /** * * String for JSON configuration keys such as treeKeepFocus, defaultReloadIgnore, etc. */ public static CONFIG_NAMES = { CHECK_FOR_CHANGE_EXTERNAL_FILES: "checkForChangeExternalFiles", DEFAULT_RELOAD_IGNORE: "defaultReloadIgnore", LEO_TREE_BROWSE: "leoTreeBrowse", TREE_KEEP_FOCUS: "treeKeepFocus", TREE_KEEP_FOCUS_WHEN_ASIDE: "treeKeepFocusWhenAside", STATUSBAR_STRING: "statusBarString", STATUSBAR_COLOR: "statusBarColor", TREE_IN_EXPLORER: "treeInExplorer", SHOW_OPEN_ASIDE: "showOpenAside", SHOW_EDIT: "showEditOnNodes", SHOW_ARROWS: "showArrowsOnNodes", SHOW_ADD: "showAddOnNodes", SHOW_MARK: "showMarkOnNodes", SHOW_CLONE: "showCloneOnNodes", SHOW_COPY: "showCopyOnNodes", SHOW_EDITION_BODY: "showEditionOnBody", SHOW_CLIPBOARD_BODY: "showClipboardOnBody", SHOW_PROMOTE_BODY: "showPromoteOnBody", SHOW_EXECUTE_BODY: "showExecuteOnBody", SHOW_EXTRACT_BODY: "showExtractOnBody", SHOW_IMPORT_BODY: "showImportOnBody", SHOW_REFRESH_BODY: "showRefreshOnBody", SHOW_HOIST_BODY: "showHoistOnBody", SHOW_MARK_BODY: "showMarkOnBody", SHOW_SORT_BODY: "showSortOnBody", INVERT_NODES: "invertNodeContrast", LEO_EDITOR_PATH: "leoEditorPath", LEO_PYTHON_COMMAND: "leoPythonCommand", AUTO_START_SERVER: "startServerAutomatically", AUTO_CONNECT: "connectToServerAutomatically", IP_ADDRESS: "connectionAddress", IP_PORT: "connectionPort", SET_DETACHED: "setDetached", LIMIT_USERS: "limitUsers" }; /** * * Configuration Defaults used in config.ts * Used when setting itself and getting parameters from vscode */ public static CONFIG_DEFAULTS = { CHECK_FOR_CHANGE_EXTERNAL_FILES: "none", // Used in leoBridge scrip, DEFAULT_RELOAD_IGNORE: "none", // Used in leoBridge scrip, LEO_TREE_BROWSE: true, TREE_KEEP_FOCUS: true, TREE_KEEP_FOCUS_WHEN_ASIDE: false, STATUSBAR_STRING: "", // Strings like "Literate", "Leo", UTF-8 also supported: \u{1F981} STATUSBAR_COLOR: "fb7c47", TREE_IN_EXPLORER: true, SHOW_OPEN_ASIDE: true, SHOW_EDIT: true, SHOW_ARROWS: false, SHOW_ADD: false, SHOW_MARK: false, SHOW_CLONE: false, SHOW_COPY: false, SHOW_EDITION_BODY: true, SHOW_CLIPBOARD_BODY: true, SHOW_PROMOTE_BODY: true, SHOW_EXECUTE_BODY: true, SHOW_EXTRACT_BODY: true, SHOW_IMPORT_BODY: true, SHOW_REFRESH_BODY: true, SHOW_HOIST_BODY: true, SHOW_MARK_BODY: true, SHOW_SORT_BODY: true, INVERT_NODES: false, LEO_PYTHON_COMMAND: "", LEO_EDITOR_PATH: "", AUTO_START_SERVER: false, AUTO_CONNECT: false, IP_ADDRESS: "localhost", IP_LOOPBACK: "127.0.0.1", IP_PORT: 32125, SET_DETACHED: true, LIMIT_USERS: 1 }; /** * * Used in 'when' clauses, set with vscode.commands.executeCommand("setContext",...) */ public static CONTEXT_FLAGS = { // Main flags for connection and opened file STARTUP_FINISHED: "leoStartupFinished", // Initial extension finished auto-server-start-connect CONNECTING: "leoConnecting", // Initial extension finished auto-server-start-connect BRIDGE_READY: "leoBridgeReady", // Connected to leoBridge TREE_OPENED: "leoTreeOpened", // At least one Leo file opened TREE_TITLED: "leoTreeTitled", // Tree is a Leo file and not a new untitled document SERVER_STARTED: "leoServerStarted", // Auto-start or manually started // 'states' flags for currently opened tree view LEO_CHANGED: "leoChanged", LEO_CAN_UNDO: "leoCanUndo", LEO_CAN_REDO: "leoCanRedo", LEO_CAN_DEMOTE: "leoCanDemote", LEO_CAN_PROMOTE: "leoCanPromote", LEO_CAN_DEHOIST: "leoCanDehoist", // 'states' flags about current selection, for visibility and commands availability SELECTED_MARKED: "leoMarked", // no need for unmarked here, use !leoMarked SELECTED_CLONE: "leoCloned", SELECTED_DIRTY: "leoDirty", SELECTED_EMPTY: "leoEmpty", SELECTED_CHILD: "leoChild", // Has children SELECTED_ATFILE: "leoAtFile", // Can be refreshed SELECTED_ROOT: "leoRoot", // ! Not given by Leo: Computed by leoInteg/vscode instead // Statusbar Flag 'keybindings in effect' LEO_SELECTED: "leoObjectSelected", // keybindings "On": Outline or body has focus // Context Flags for 'when' clauses, used concatenated, for each outline node NODE_MARKED: "leoNodeMarked", // Selected node is marked NODE_UNMARKED: "leoNodeUnmarked", // Selected node is unmarked (Needed for regexp) NODE_ATFILE: "leoNodeAtFile", // Selected node is an @file or @clean, etc... NODE_CLONED: "leoNodeCloned", NODE_ROOT: "leoNodeRoot", NODE_NOT_ROOT: "leoNodeNotRoot", // Flags for Leo documents tree view icons and hover node command buttons DOCUMENT_SELECTED_TITLED: "leoDocumentSelectedTitled", DOCUMENT_TITLED: "leoDocumentTitled", DOCUMENT_SELECTED_UNTITLED: "leoDocumentSelectedUntitled", DOCUMENT_UNTITLED: "leoDocumentUntitled", // Flags that match specific LeoInteg config settings LEO_TREE_BROWSE: Constants.CONFIG_NAMES.LEO_TREE_BROWSE, // Force ar'jan's suggestion of Leo's tree behavior override TREE_IN_EXPLORER: Constants.CONFIG_NAMES.TREE_IN_EXPLORER, // Leo outline also in the explorer view SHOW_OPEN_ASIDE: Constants.CONFIG_NAMES.SHOW_OPEN_ASIDE, // Show 'open aside' in context menu SHOW_EDIT: Constants.CONFIG_NAMES.SHOW_EDIT, // Hover Icons on outline nodes SHOW_ARROWS: Constants.CONFIG_NAMES.SHOW_ARROWS, // Hover Icons on outline nodes SHOW_ADD: Constants.CONFIG_NAMES.SHOW_ADD, // Hover Icons on outline nodes SHOW_MARK: Constants.CONFIG_NAMES.SHOW_MARK, // Hover Icons on outline nodes SHOW_CLONE: Constants.CONFIG_NAMES.SHOW_CLONE, // Hover Icons on outline nodes SHOW_COPY: Constants.CONFIG_NAMES.SHOW_COPY, // Hover Icons on outline nodes AUTO_START_SERVER: Constants.CONFIG_NAMES.AUTO_START_SERVER, // Used at startup AUTO_CONNECT: Constants.CONFIG_NAMES.AUTO_CONNECT, // Used at startup SHOW_EDITION_BODY: Constants.CONFIG_NAMES.SHOW_EDITION_BODY, SHOW_CLIPBOARD_BODY: Constants.CONFIG_NAMES.SHOW_CLIPBOARD_BODY, SHOW_PROMOTE_BODY: Constants.CONFIG_NAMES.SHOW_PROMOTE_BODY, SHOW_EXECUTE_BODY: Constants.CONFIG_NAMES.SHOW_EXECUTE_BODY, SHOW_EXTRACT_BODY: Constants.CONFIG_NAMES.SHOW_EXTRACT_BODY, SHOW_IMPORT_BODY: Constants.CONFIG_NAMES.SHOW_IMPORT_BODY, SHOW_REFRESH_BODY: Constants.CONFIG_NAMES.SHOW_REFRESH_BODY, SHOW_HOIST_BODY: Constants.CONFIG_NAMES.SHOW_HOIST_BODY, SHOW_MARK_BODY: Constants.CONFIG_NAMES.SHOW_MARK_BODY, SHOW_SORT_BODY: Constants.CONFIG_NAMES.SHOW_SORT_BODY }; /** * * Command strings to be used with vscode.commands.executeCommand * See https://code.visualstudio.com/api/extension-guides/command#programmatically-executing-a-command */ public static VSCODE_COMMANDS = { SET_CONTEXT: "setContext", CLOSE_ACTIVE_EDITOR: "workbench.action.closeActiveEditor", QUICK_OPEN: "workbench.action.quickOpen" }; /** * * Actions that can be invoked by Leo through leobridge */ public static ASYNC_ACTIONS = { ASYNC_LOG: "log", ASYNC_REFRESH: "refresh", ASYNC_ASK: "ask", ASYNC_WARN: "warn", ASYNC_INFO: "info", ASYNC_INTERVAL: "interval" }; /** * * When async action was ASYNC_INFO */ public static ASYNC_INFO_MESSAGE_CODES = { ASYNC_REFRESHED: "refreshed", ASYNC_IGNORED: "ignored" }; /** * * runAskYesNoDialog or runAskOkDialog result codes, used when async action requires a response */ public static ASYNC_ASK_RETURN_CODES = { YES: "yes", NO: "no", YES_ALL: "yes-all", NO_ALL: "no-all", OK: "ok" }; /** * * Table for converting Leo languages names for the currently opened body pane * Used in showBody method of leoIntegration.ts */ public static LANGUAGE_CODES: { [key: string]: string | undefined } = { cplusplus: 'cpp', md: 'markdown', rest: 'restructuredtext', rst: 'restructuredtext' }; /** * * Commands for leobridgeserver.py * A Command is a string, which is either: * - The name of public method in leoserver.py, prefixed with '!'. * - The name of a Leo command, prefixed with '-' * - The name of a method of a Leo class, without prefix. */ public static LEOBRIDGE = { TEST: "!test", DO_NOTHING: "!do_nothing", GET_VERSION: "!get_version", // * Server Commands GET_COMMANDS: "!get_all_leo_commands", // "getCommands", APPLY_CONFIG: "!set_config", // "applyConfig", ASK_RESULT: "!set_ask_result", // "askResult", // * GUI GET_ALL_GNX: "!get_all_gnx", // "getAllGnx", GET_BODY_LENGTH: "!get_body_length", // "getBodyLength", GET_BODY_STATES: "!get_body_states", // "getBodyStates", GET_BODY: "!get_body", // "getBody", GET_PARENT: "!get_parent", // "getParent", GET_CHILDREN: "!get_children", // "getChildren", SET_SELECTED_NODE: "!set_current_position", // "setSelectedNode", SET_BODY: "!set_body", // "setBody", SET_SELECTION: "!set_selection", // "setSelection", SET_HEADLINE: "!set_headline", // "setNewHeadline", EXPAND_NODE: "!expand_node", // "expandNode", COLLAPSE_NODE: "!contract_node", // "collapseNode", CONTRACT_ALL: "contractAllHeadlines", GET_STATES: "!get_ui_states", // "getStates", GET_UA: "!get_ua", SET_UA_MEMBER: "!set_ua_member", SET_UA: "!set_ua", // * Leo Documents GET_OPENED_FILES: "!get_all_open_commanders", //"getOpenedFiles", SET_OPENED_FILE: "!set_opened_file", // "setOpenedFile", OPEN_FILE: "!open_file", // "openFile", IMPORT_ANY_FILE: "!import_any_file", // "importAnyFile", OPEN_FILES: "!open_files", // "openFiles", CLOSE_FILE: "!close_file", // "closeFile", SAVE_FILE: "!save_file", // "saveFile", // * @-Buttons GET_BUTTONS: "!get_buttons", // "getButtons", REMOVE_BUTTON: "!remove_button", // "removeButton", GOTO_SCRIPT: "!goto_script", // "goto Script command", CLICK_BUTTON: "!click_button", // "clickButton", // * Goto operations PAGE_UP: "!page_up", // "pageUp", PAGE_DOWN: "!page_down", // "pageDown", GOTO_FIRST_VISIBLE: "goToFirstVisibleNode", GOTO_LAST_VISIBLE: "goToLastVisibleNode", GOTO_LAST_SIBLING: "goToLastSibling", GOTO_NEXT_VISIBLE: "selectVisNext", GOTO_PREV_VISIBLE: "selectVisBack", GOTO_NEXT_MARKED: "goToNextMarkedHeadline", GOTO_NEXT_CLONE: "goToNextClone", CONTRACT_OR_GO_LEFT: "contractNodeOrGoToParent", EXPAND_AND_GO_RIGHT: "expandNodeAndGoToFirstChild", // * Leo Operations MARK_PNODE: "!mark_node", // "markPNode", UNMARK_PNODE: "!unmark_node", // "unmarkPNode", COPY_PNODE: "copyOutline", CUT_PNODE: "!cut_node", // "cutPNode", PASTE_PNODE: "pasteOutline", PASTE_CLONE_PNODE: "pasteOutlineRetainingClones", DELETE_PNODE: "!delete_node", // "deletePNode", MOVE_PNODE_DOWN: "moveOutlineDown", MOVE_PNODE_LEFT: "moveOutlineLeft", MOVE_PNODE_RIGHT: "moveOutlineRight", MOVE_PNODE_UP: "moveOutlineUp", INSERT_PNODE: "!insert_node", // "insertPNode", INSERT_NAMED_PNODE: "!insert_named_node", // "insertNamedPNode", INSERT_CHILD_PNODE: "!insert_child_node", INSERT_CHILD_NAMED_PNODE: "!insert_child_named_node", CLONE_PNODE: "!clone_node", // "clonePNode", PROMOTE_PNODE: "promote", DEMOTE_PNODE: "demote", REFRESH_FROM_DISK_PNODE: "refreshFromDisk", WRITE_AT_FILE_NODES: '-write-at-file-nodes', WRITE_DIRTY_AT_FILE_NODES: '-write-dirty-at-file-nodes', SORT_CHILDREN: "sortChildren", SORT_SIBLINGS: "sortSiblings", UNDO: "!undo", REDO: "!redo", EXECUTE_SCRIPT: "executeScript", HOIST_PNODE: "hoist", DEHOIST: "dehoist", EXTRACT: "extract", EXTRACT_NAMES: "extractSectionNames", COPY_MARKED: "copyMarked", DIFF_MARKED_NODES: "-diff-marked-nodes", MARK_CHANGED_ITEMS: "markChangedHeadlines", MARK_SUBHEADS: "markSubheads", UNMARK_ALL: "unmarkAll", CLONE_MARKED_NODES: "cloneMarked", DELETE_MARKED_NODES: "deleteMarked", MOVE_MARKED_NODES: "moveMarked", GIT_DIFF: "gitDiff", GET_FOCUS: "!get_focus", GET_SEARCH_SETTINGS: "!get_search_settings", SET_SEARCH_SETTINGS: "!set_search_settings", START_SEARCH: "!start_search", FIND_ALL: "!find_all", FIND_NEXT: "!find_next", FIND_PREVIOUS: "!find_previous", FIND_VAR: "!find_var", FIND_DEF: "!find_def", REPLACE: "!replace", REPLACE_THEN_FIND: "!replace_then_find", REPLACE_ALL: "!replace_all", GOTO_GLOBAL_LINE: "!goto_global_line", TAG_CHILDREN: "!tag_children", CLONE_FIND_TAG: "!clone_find_tag", CLONE_FIND_ALL: "!clone_find_all", CLONE_FIND_ALL_FLATTENED: "!clone_find_all_flattened", CLONE_FIND_MARKED: "!clone_find_all_marked", CLONE_FIND_FLATTENED_MARKED: "!clone_find_all_flattened_marked", GOTO_PREV_HISTORY: "goToPrevHistory", GOTO_NEXT_HISTORY: "goToNextHistory" }; /** * * All commands this expansion exposes (in package.json, contributes > commands) */ public static COMMANDS = { // * Access to the Settings/Welcome Webview SHOW_WELCOME: Constants.NAME + ".showWelcomePage", // Always available: not in the commandPalette section of package.json SHOW_SETTINGS: Constants.NAME + ".showSettingsPage", // Always available: not in the commandPalette section of package.json STATUS_BAR: Constants.NAME + ".statusBar", // Status Bar Click Command // * LeoBridge CHOOSE_LEO_FOLDER: Constants.NAME + ".chooseLeoFolder", START_SERVER: Constants.NAME + ".startServer", STOP_SERVER: Constants.NAME + ".stopServer", CONNECT: Constants.NAME + ".connectToServer", SET_OPENED_FILE: Constants.NAME + ".setOpenedFile", OPEN_FILE: Constants.NAME + ".openLeoFile", // sets focus on BODY CLEAR_RECENT_FILES: Constants.NAME + ".clearRecentFiles", IMPORT_ANY_FILE: Constants.NAME + ".importAnyFile", RECENT_FILES: Constants.NAME + ".recentLeoFiles", // shows recent Leo files, opens one on selection SWITCH_FILE: Constants.NAME + ".switchLeoFile", NEW_FILE: Constants.NAME + ".newLeoFile", SAVE_FILE: Constants.NAME + ".saveLeoFile", // SAVE_DISABLED: Constants.NAME + ".saveLeoFileDisabled", // Disabled - nop SAVE_FILE_FO: Constants.NAME + ".saveLeoFileFromOutline", SAVE_AS_FILE: Constants.NAME + ".saveAsLeoFile", SAVE_AS_LEOJS: Constants.NAME + ".saveAsLeoJsFile", CLOSE_FILE: Constants.NAME + ".closeLeoFile", CLICK_BUTTON: Constants.NAME + ".clickButton", REMOVE_BUTTON: Constants.NAME + ".removeButton", GOTO_SCRIPT: Constants.NAME + ".gotoScript", MINIBUFFER: Constants.NAME + ".minibuffer", GIT_DIFF: Constants.NAME + ".gitDiff", // * Outline selection SELECT_NODE: Constants.NAME + ".selectTreeNode", OPEN_ASIDE: Constants.NAME + ".openAside", // * Goto operations that always finish with focus in outline PAGE_UP: Constants.NAME + ".pageUp", PAGE_DOWN: Constants.NAME + ".pageDown", GOTO_FIRST_VISIBLE: Constants.NAME + ".gotoFirstVisible", GOTO_LAST_VISIBLE: Constants.NAME + ".gotoLastVisible", GOTO_LAST_SIBLING: Constants.NAME + ".gotoLastSibling", GOTO_NEXT_VISIBLE: Constants.NAME + ".gotoNextVisible", GOTO_PREV_VISIBLE: Constants.NAME + ".gotoPrevVisible", GOTO_NEXT_MARKED: Constants.NAME + ".gotoNextMarked", GOTO_NEXT_CLONE: Constants.NAME + ".gotoNextClone", GOTO_NEXT_CLONE_SELECTION: Constants.NAME + ".gotoNextCloneSelection", GOTO_NEXT_CLONE_SELECTION_FO: Constants.NAME + ".gotoNextCloneSelectionFromOutline", CONTRACT_OR_GO_LEFT: Constants.NAME + ".contractOrGoLeft", EXPAND_AND_GO_RIGHT: Constants.NAME + ".expandAndGoRight", // * Leo Operations UNDO: Constants.NAME + ".undo", // From command Palette UNDO_FO: Constants.NAME + ".undoFromOutline", // from button, return focus on OUTLINE UNDO_DISABLED: Constants.NAME + ".undoDisabled", // Disabled - nop REDO: Constants.NAME + ".redo", // From command Palette REDO_FO: Constants.NAME + ".redoFromOutline", // from button, return focus on OUTLINE REDO_DISABLED: Constants.NAME + ".redoDisabled", // Disabled - nop EXECUTE: Constants.NAME + ".executeScript", SHOW_BODY: Constants.NAME + ".showBody", SHOW_OUTLINE: Constants.NAME + ".showOutline", SHOW_LOG: Constants.NAME + ".showLogPane", SORT_CHILDREN: Constants.NAME + ".sortChildrenSelection", SORT_CHILDREN_FO: Constants.NAME + ".sortChildrenSelectionFromOutline", SORT_SIBLING: Constants.NAME + ".sortSiblingsSelection", SORT_SIBLING_FO: Constants.NAME + ".sortSiblingsSelectionFromOutline", CONTRACT_ALL: Constants.NAME + ".contractAll", // From command Palette CONTRACT_ALL_FO: Constants.NAME + ".contractAllFromOutline", // from button, return focus on OUTLINE PREV_NODE: Constants.NAME + ".prev", PREV_NODE_FO: Constants.NAME + ".prevFromOutline", NEXT_NODE: Constants.NAME + ".next", NEXT_NODE_FO: Constants.NAME + ".nextFromOutline", // * Commands from tree panel buttons or context: focus on OUTLINE MARK: Constants.NAME + ".mark", UNMARK: Constants.NAME + ".unmark", COPY: Constants.NAME + ".copyNode", CUT: Constants.NAME + ".cutNode", PASTE: Constants.NAME + ".pasteNode", PASTE_CLONE: Constants.NAME + ".pasteNodeAsClone", DELETE: Constants.NAME + ".delete", HEADLINE: Constants.NAME + ".editHeadline", MOVE_DOWN: Constants.NAME + ".moveOutlineDown", MOVE_LEFT: Constants.NAME + ".moveOutlineLeft", MOVE_RIGHT: Constants.NAME + ".moveOutlineRight", MOVE_UP: Constants.NAME + ".moveOutlineUp", INSERT: Constants.NAME + ".insertNode", INSERT_CHILD: Constants.NAME + ".insertChildNode", CLONE: Constants.NAME + ".cloneNode", PROMOTE: Constants.NAME + ".promote", DEMOTE: Constants.NAME + ".demote", REFRESH_FROM_DISK: Constants.NAME + ".refreshFromDisk", WRITE_AT_FILE_NODES: Constants.NAME + ".writeAtFileNodes", WRITE_AT_FILE_NODES_FO: Constants.NAME + ".writeAtFileNodesFromOutline", WRITE_DIRTY_AT_FILE_NODES: Constants.NAME + ".writeDirtyAtFileNodes", WRITE_DIRTY_AT_FILE_NODES_FO: Constants.NAME + ".writeDirtyAtFileNodesFromOutline", // * Commands from keyboard, while focus on BODY (command-palette returns to BODY for now) MARK_SELECTION: Constants.NAME + ".markSelection", UNMARK_SELECTION: Constants.NAME + ".unmarkSelection", COPY_SELECTION: Constants.NAME + ".copyNodeSelection", // Nothing to refresh/focus so no "FO" version CUT_SELECTION: Constants.NAME + ".cutNodeSelection", PASTE_SELECTION: Constants.NAME + ".pasteNodeAtSelection", PASTE_CLONE_SELECTION: Constants.NAME + ".pasteNodeAsCloneAtSelection", DELETE_SELECTION: Constants.NAME + ".deleteSelection", HEADLINE_SELECTION: Constants.NAME + ".editSelectedHeadline", MOVE_DOWN_SELECTION: Constants.NAME + ".moveOutlineDownSelection", MOVE_LEFT_SELECTION: Constants.NAME + ".moveOutlineLeftSelection", MOVE_RIGHT_SELECTION: Constants.NAME + ".moveOutlineRightSelection", MOVE_UP_SELECTION: Constants.NAME + ".moveOutlineUpSelection", INSERT_SELECTION: Constants.NAME + ".insertNodeSelection", // Can be interrupted INSERT_SELECTION_INTERRUPT: Constants.NAME + ".insertNodeSelectionInterrupt", // Interrupted version INSERT_CHILD_SELECTION: Constants.NAME + ".insertChildNodeSelection", // Can be interrupted INSERT_CHILD_SELECTION_INTERRUPT: Constants.NAME + ".insertChildNodeSelectionInterrupt", // Can be interrupted CLONE_SELECTION: Constants.NAME + ".cloneNodeSelection", PROMOTE_SELECTION: Constants.NAME + ".promoteSelection", DEMOTE_SELECTION: Constants.NAME + ".demoteSelection", REFRESH_FROM_DISK_SELECTION: Constants.NAME + ".refreshFromDiskSelection", // * Commands from keyboard, while focus on OUTLINE MARK_SELECTION_FO: Constants.NAME + ".markSelectionFromOutline", UNMARK_SELECTION_FO: Constants.NAME + ".unmarkSelectionFromOutline", // COPY_SELECTION Nothing to refresh/focus for "copy a node" so no "FO" version CUT_SELECTION_FO: Constants.NAME + ".cutNodeSelectionFromOutline", PASTE_SELECTION_FO: Constants.NAME + ".pasteNodeAtSelectionFromOutline", PASTE_CLONE_SELECTION_FO: Constants.NAME + ".pasteNodeAsCloneAtSelectionFromOutline", DELETE_SELECTION_FO: Constants.NAME + ".deleteSelectionFromOutline", HEADLINE_SELECTION_FO: Constants.NAME + ".editSelectedHeadlineFromOutline", MOVE_DOWN_SELECTION_FO: Constants.NAME + ".moveOutlineDownSelectionFromOutline", MOVE_LEFT_SELECTION_FO: Constants.NAME + ".moveOutlineLeftSelectionFromOutline", MOVE_RIGHT_SELECTION_FO: Constants.NAME + ".moveOutlineRightSelectionFromOutline", MOVE_UP_SELECTION_FO: Constants.NAME + ".moveOutlineUpSelectionFromOutline", INSERT_SELECTION_FO: Constants.NAME + ".insertNodeSelectionFromOutline", INSERT_CHILD_SELECTION_FO: Constants.NAME + ".insertChildNodeSelectionFromOutline", CLONE_SELECTION_FO: Constants.NAME + ".cloneNodeSelectionFromOutline", PROMOTE_SELECTION_FO: Constants.NAME + ".promoteSelectionFromOutline", DEMOTE_SELECTION_FO: Constants.NAME + ".demoteSelectionFromOutline", REFRESH_FROM_DISK_SELECTION_FO: Constants.NAME + ".refreshFromDiskSelectionFromOutline", HOIST: Constants.NAME + ".hoistNode", HOIST_SELECTION: Constants.NAME + ".hoistSelection", HOIST_SELECTION_FO: Constants.NAME + ".hoistSelectionFromOutline", DEHOIST: Constants.NAME + ".deHoist", DEHOIST_FO: Constants.NAME + ".deHoistFromOutline", EXTRACT: Constants.NAME + ".extract", EXTRACT_NAMES: Constants.NAME + ".extractNames", COPY_MARKED: Constants.NAME + ".copyMarked", DIFF_MARKED_NODES: Constants.NAME + ".diffMarkedNodes", MARK_CHANGED_ITEMS: Constants.NAME + ".markChangedItems", MARK_SUBHEADS: Constants.NAME + ".markSubheads", UNMARK_ALL: Constants.NAME + ".unmarkAll", CLONE_MARKED_NODES: Constants.NAME + ".cloneMarkedNodes", DELETE_MARKED_NODES: Constants.NAME + ".deleteMarkedNodes", MOVE_MARKED_NODES: Constants.NAME + ".moveMarkedNodes", START_SEARCH: Constants.NAME + ".startSearch", FIND_ALL: Constants.NAME + ".findAll", FIND_NEXT: Constants.NAME + ".findNext", FIND_NEXT_FO: Constants.NAME + ".findNextFromOutline", FIND_PREVIOUS: Constants.NAME + ".findPrevious", FIND_PREVIOUS_FO: Constants.NAME + ".findPreviousFromOutline", FIND_VAR: Constants.NAME + ".findVar", FIND_DEF: Constants.NAME + ".findDef", REPLACE: Constants.NAME + ".replace", REPLACE_FO: Constants.NAME + ".replaceFromOutline", REPLACE_THEN_FIND: Constants.NAME + ".replaceThenFind", REPLACE_THEN_FIND_FO: Constants.NAME + ".replaceThenFindFromOutline", REPLACE_ALL: Constants.NAME + ".replaceAll", CLONE_FIND_ALL: Constants.NAME + ".cloneFindAll", CLONE_FIND_ALL_FLATTENED: Constants.NAME + ".cloneFindAllFlattened", CLONE_FIND_TAG: Constants.NAME + ".cloneFindTag", CLONE_FIND_MARKED: Constants.NAME + ".cloneFindMarked", CLONE_FIND_FLATTENED_MARKED: Constants.NAME + ".cloneFindFlattenedMarked", GOTO_GLOBAL_LINE: Constants.NAME + ".gotoGlobalLine", TAG_CHILDREN: Constants.NAME + ".tagChildren", SET_FIND_EVERYWHERE_OPTION: Constants.NAME + ".setFindEverywhereOption", SET_FIND_NODE_ONLY_OPTION: Constants.NAME + ".setFindNodeOnlyOption", SET_FIND_SUBOUTLINE_ONLY_OPTION: Constants.NAME + ".setFindSuboutlineOnlyOption", TOGGLE_FIND_IGNORE_CASE_OPTION: Constants.NAME + ".toggleFindIgnoreCaseOption", TOGGLE_FIND_MARK_CHANGES_OPTION: Constants.NAME + ".toggleFindMarkChangesOption", TOGGLE_FIND_MARK_FINDS_OPTION: Constants.NAME + ".toggleFindMarkFindsOption", TOGGLE_FIND_REGEXP_OPTION: Constants.NAME + ".toggleFindRegexpOption", TOGGLE_FIND_WORD_OPTION: Constants.NAME + ".toggleFindWordOption", TOGGLE_FIND_SEARCH_BODY_OPTION: Constants.NAME + ".toggleFindSearchBodyOption", TOGGLE_FIND_SEARCH_HEADLINE_OPTION: Constants.NAME + ".toggleFindSearchHeadlineOption", SET_ENABLE_PREVIEW: Constants.NAME + ".setEnablePreview", CLEAR_CLOSE_EMPTY_GROUPS: Constants.NAME + ".clearCloseEmptyGroups", SET_CLOSE_ON_FILE_DELETE: Constants.NAME + ".setCloseOnFileDelete", }; /** * * Overridden 'good' minibuffer commands */ public static MINIBUFFER_OVERRIDDEN_COMMANDS: { [key: string]: string } = { "tag-children": Constants.COMMANDS.TAG_CHILDREN, "clone-find-tag": Constants.COMMANDS.CLONE_FIND_TAG, "import-file": Constants.COMMANDS.IMPORT_ANY_FILE, "redo": Constants.COMMANDS.REDO, "undo": Constants.COMMANDS.UNDO, "clone-find-all": Constants.COMMANDS.CLONE_FIND_ALL, "clone-find-all-flattened": Constants.COMMANDS.CLONE_FIND_ALL_FLATTENED, 'import-MORE-files': Constants.COMMANDS.IMPORT_ANY_FILE, 'import-free-mind-files': Constants.COMMANDS.IMPORT_ANY_FILE, 'import-jupyter-notebook': Constants.COMMANDS.IMPORT_ANY_FILE, 'import-legacy-external-files': Constants.COMMANDS.IMPORT_ANY_FILE, 'import-mind-jet-files': Constants.COMMANDS.IMPORT_ANY_FILE, 'import-tabbed-files': Constants.COMMANDS.IMPORT_ANY_FILE, 'import-todo-text-files': Constants.COMMANDS.IMPORT_ANY_FILE, 'import-zim-folder': Constants.COMMANDS.IMPORT_ANY_FILE, 'file-new': Constants.COMMANDS.NEW_FILE, 'file-open-by-name': Constants.COMMANDS.OPEN_FILE, 'new': Constants.COMMANDS.NEW_FILE, 'open-outline': Constants.COMMANDS.OPEN_FILE, 'file-save': Constants.COMMANDS.SAVE_FILE, 'file-save-as': Constants.COMMANDS.SAVE_AS_FILE, 'file-save-as-leojs': Constants.COMMANDS.SAVE_AS_LEOJS, 'file-save-as-unzipped': Constants.COMMANDS.SAVE_AS_FILE, 'file-save-by-name': Constants.COMMANDS.SAVE_AS_FILE, 'file-save-to': Constants.COMMANDS.SAVE_AS_FILE, 'save': Constants.COMMANDS.SAVE_FILE, 'save-as': Constants.COMMANDS.SAVE_AS_FILE, 'save-file': Constants.COMMANDS.SAVE_FILE, 'save-file-as': Constants.COMMANDS.SAVE_AS_FILE, 'save-file-as-leojs': Constants.COMMANDS.SAVE_AS_LEOJS, 'save-file-as-unzipped': Constants.COMMANDS.SAVE_AS_FILE, 'save-file-by-name': Constants.COMMANDS.SAVE_AS_FILE, 'save-file-to': Constants.COMMANDS.SAVE_AS_FILE, 'save-to': Constants.COMMANDS.SAVE_AS_FILE, 'clone-find-all-flattened-marked': Constants.COMMANDS.CLONE_FIND_FLATTENED_MARKED, 'clone-find-all-marked': Constants.COMMANDS.CLONE_FIND_MARKED, 'clone-marked-nodes': Constants.COMMANDS.CLONE_MARKED_NODES, 'cfa': Constants.COMMANDS.CLONE_FIND_ALL, 'cfam': Constants.COMMANDS.CLONE_FIND_MARKED, 'cff': Constants.COMMANDS.CLONE_FIND_ALL_FLATTENED, 'cffm': Constants.COMMANDS.CLONE_FIND_FLATTENED_MARKED, 'cft': Constants.COMMANDS.CLONE_FIND_TAG, 'git-diff': Constants.COMMANDS.GIT_DIFF, 'gd': Constants.COMMANDS.GIT_DIFF, 'find-tab-open': Constants.COMMANDS.START_SEARCH, 'find-clone-all': Constants.COMMANDS.CLONE_FIND_ALL, 'find-clone-all-flattened': Constants.COMMANDS.CLONE_FIND_ALL_FLATTENED, 'find-clone-tag': Constants.COMMANDS.CLONE_FIND_TAG, 'find-all': Constants.COMMANDS.FIND_ALL, 'start-search': Constants.COMMANDS.START_SEARCH, 'find-next': Constants.COMMANDS.FIND_NEXT, 'find-prev': Constants.COMMANDS.FIND_PREVIOUS, 'search-backward': Constants.COMMANDS.FIND_NEXT, 'search-forward': Constants.COMMANDS.FIND_PREVIOUS, 'find-var': Constants.COMMANDS.FIND_VAR, 'find-def': Constants.COMMANDS.FIND_DEF, 'replace': Constants.COMMANDS.REPLACE, 'replace-all': Constants.COMMANDS.REPLACE_ALL, 'change-all': Constants.COMMANDS.REPLACE_ALL, 'change-then-find': Constants.COMMANDS.REPLACE_THEN_FIND, 'replace-then-find': Constants.COMMANDS.REPLACE_THEN_FIND, 'show-find-options': Constants.COMMANDS.START_SEARCH, 'toggle-find-ignore-case-option': Constants.COMMANDS.TOGGLE_FIND_IGNORE_CASE_OPTION, 'toggle-find-in-body-option': Constants.COMMANDS.TOGGLE_FIND_SEARCH_BODY_OPTION, 'toggle-find-in-headline-option': Constants.COMMANDS.TOGGLE_FIND_SEARCH_HEADLINE_OPTION, 'toggle-find-mark-changes-option': Constants.COMMANDS.TOGGLE_FIND_MARK_CHANGES_OPTION, 'toggle-find-mark-finds-option': Constants.COMMANDS.TOGGLE_FIND_MARK_FINDS_OPTION, 'toggle-find-regex-option': Constants.COMMANDS.TOGGLE_FIND_REGEXP_OPTION, 'toggle-find-word-option': Constants.COMMANDS.TOGGLE_FIND_WORD_OPTION, 'goto-next-history-node': Constants.COMMANDS.PREV_NODE, 'goto-prev-history-node': Constants.COMMANDS.NEXT_NODE, }; }
the_stack
* based on commit "cf1e602" * 文件结构 * * -模块 * -命名空间 * -全局 * * 未加入:WidgetsBasedAutomation、Shell、Thread、UI、Work with Java * */ declare module 'global' { /** * 表示一个点(坐标)。 */ interface Point { x: number; y: number; } /** * app模块提供一系列函数,用于使用其他应用、与其他应用交互。例如发送意图、打开文件、发送邮件等。 */ namespace app { /** * 通过应用名称启动应用。如果该名称对应的应用不存在,则返回false; 否则返回true。如果该名称对应多个应用,则只启动其中某一个。 */ function launchApp(appName: string): boolean; /** * 通过应用包名启动应用。如果该包名对应的应用不存在,则返回false;否则返回true。 */ function launch(packageName: string): boolean; /** * 通过应用包名启动应用。如果该包名对应的应用不存在,则返回false;否则返回true。 */ function launchPackage(packageName: string): boolean; /** * 获取应用名称对应的已安装的应用的包名。如果该找不到该应用,返回null;如果该名称对应多个应用,则只返回其中某一个的包名。 */ function getPackageName(appName: string): string; /** * 获取应用包名对应的已安装的应用的名称。如果该找不到该应用,返回null。 */ function getAppName(packageName: string): string; /** * 打开应用的详情页(设置页)。如果找不到该应用,返回false; 否则返回true。 */ function openAppSetting(packageName: string): boolean; /** * 用其他应用查看文件。文件不存在的情况由查看文件的应用处理。如果找不出可以查看该文件的应用,则抛出ActivityNotException。 * * @throws ActivityNotException */ function viewFile(path: string): void; /** * 用其他应用编辑文件。文件不存在的情况由编辑文件的应用处理。如果找不出可以编辑该文件的应用,则抛出ActivityNotException。 * * @throws ActivityNotException */ function editFile(path: string): void; /** * 卸载应用。执行后会会弹出卸载应用的提示框。如果该包名的应用未安装,由应用卸载程序处理,可能弹出"未找到应用"的提示。 */ function uninstall(packageName: string): void; /** * 用浏览器打开网站url。网站的Url,如果不以"http:// "或"https:// "开头则默认是"http:// "。 */ function openUrl(url: string): void; /** * 发送邮件的参数,这些选项均是可选的。 */ interface SendEmailOptions { /** * 收件人的邮件地址。如果有多个收件人,则用字符串数组表示 */ email?: string | string[]; /** * 抄送收件人的邮件地址。如果有多个抄送收件人,则用字符串数组表示 */ cc?: string | string[]; /** * 密送收件人的邮件地址。如果有多个密送收件人,则用字符串数组表示 */ bcc?: string | string[]; /** * 邮件主题(标题) */ subject?: string; /** * 邮件正文 */ text?: string; /** * 附件的路径。 */ attachment?: string; } /** * 根据选项options调用邮箱应用发送邮件。如果没有安装邮箱应用,则抛出ActivityNotException。 */ function sendEmail(options: SendEmailOptions): void; /** * 启动Auto.js的特定界面。该函数在Auto.js内运行则会打开Auto.js内的界面,在打包应用中运行则会打开打包应用的相应界面。 */ function startActivity(name: 'console' | 'settings'): void; /** * Intent(意图) 是一个消息传递对象,您可以使用它从其他应用组件请求操作。尽管 Intent 可以通过多种方式促进组件之间的通信. */ interface Intent { } /** * 构造意图Intent对象所需设置。 */ interface IntentOptions { action?: string; type?: string; data?: string; category?: string[]; packageName?: string; className?: string; extras?: Object; } /** * 根据选项,构造一个意图Intent对象。 */ function intent(options: IntentOptions): Intent; /** * 根据选项构造一个Intent,并启动该Activity。 */ function startActivity(intent: Intent): void; /** * 根据选项构造一个Intent,并发送该广播。 */ function sendBroadcast(intent: Intent): void; } /** * 通过应用名称启动应用。如果该名称对应的应用不存在,则返回false; 否则返回true。如果该名称对应多个应用,则只启动其中某一个。 */ function launchApp(appName: string): boolean; /** * 通过应用包名启动应用。如果该包名对应的应用不存在,则返回false;否则返回true。 */ function launch(packageName: string): boolean; /** * 获取应用名称对应的已安装的应用的包名。如果该找不到该应用,返回null;如果该名称对应多个应用,则只返回其中某一个的包名。 */ function getPackageName(appName: string): string; /** * 获取应用名称对应的已安装的应用的包名。如果该找不到该应用,返回null;如果该名称对应多个应用,则只返回其中某一个的包名。 */ function getPackageName(appName: string): string; /** * 获取应用包名对应的已安装的应用的名称。如果该找不到该应用,返回null。 */ function getAppName(packageName: string): string; /** * 打开应用的详情页(设置页)。如果找不到该应用,返回false; 否则返回true。 */ function openAppSetting(packageName: string): boolean; // interface Console { // show(): void; // verbose(): void; // } /** * 控制台模块提供了一个和Web浏览器中相似的用于调试的控制台。用于输出一些调试信息、中间结果等。 console模块中的一些函数也可以直接作为全局函数使用,例如log, print等。 */ namespace console { /** * 显示控制台。这会显示一个控制台的悬浮窗(需要悬浮窗权限)。 */ function show(): void; /** * 隐藏控制台悬浮窗。 */ function hide(): void; /** * 清空控制台。 */ function clear(): void; /** * 打印到控制台,并带上换行符。 可以传入多个参数,第一个参数作为主要信息,其他参数作为类似于 printf(3) 中的代替值(参数都会传给 util.format())。 */ function log(data: string, ...args: any[]): void; /** * 与console.log类似,但输出结果以灰色字体显示。输出优先级低于log,用于输出观察性质的信息。 */ function verbose(data: string, ...args: any[]): void; /** * 与console.log类似,但输出结果以绿色字体显示。输出优先级高于log, 用于输出重要信息。 */ function info(data: string, ...args: any[]): void; /** * 与console.log类似,但输出结果以蓝色字体显示。输出优先级高于info, 用于输出警告信息。 */ function warn(data: string, ...args: any[]): void; /** * 与console.log类似,但输出结果以红色字体显示。输出优先级高于warn, 用于输出错误信息。 */ function error(data: string, ...args: any[]): void; /** * 断言。如果value为false则输出错误信息message并停止脚本运行。 */ function assert(value: boolean, message: string); /** * 与console.log一样输出信息,并在控制台显示输入框等待输入。按控制台的确认按钮后会将输入的字符串用eval计算后返回。 */ function input(data: string, ...args: any[]): string | number | boolean; /** * 与console.log一样输出信息,并在控制台显示输入框等待输入。按控制台的确认按钮后会将输入的字符串直接返回。 */ function rawInput(data: string, ...args: any[]): string; /** * 设置控制台的大小,单位像素。 */ function setSize(wight: number, height: number): void; /** * 设置控制台的位置,单位像素。 */ function setPosition(x: number, y: number): void; } /** * 打印到控制台,并带上换行符。 可以传入多个参数,第一个参数作为主要信息,其他参数作为类似于 printf(3) 中的代替值(参数都会传给 util.format())。 */ function log(data: string, ...args: any[]): void; /** * 相当于log(text)。 */ function print(message: string | Object): void; /* 基于坐标的触摸模拟 */ /** * 设置脚本坐标点击所适合的屏幕宽高。如果脚本运行时,屏幕宽度不一致会自动放缩坐标。 */ function setScreenMetrics(width: number, height: number): void; /* 安卓7.0以上的触摸和手势模拟 */ /** * Android7.0以上 * * 模拟点击坐标(x, y)大约150毫秒,并返回是否点击成功。只有在点击执行完成后脚本才继续执行。 */ function click(x: number, y: number): void; /** * Android7.0以上 * * 模拟长按坐标(x, y), 并返回是否成功。只有在长按执行完成(大约600毫秒)时脚本才会继续执行。 */ function longClick(x: number, y: number): void; /** * Android7.0以上 * * 模拟按住坐标(x, y), 并返回是否成功。只有按住操作执行完成时脚本才会继续执行。 * * 如果按住时间过短,那么会被系统认为是点击;如果时长超过500毫秒,则认为是长按。 */ function press(x: number, y: number, duration: number): void; /** * 模拟从坐标(x1, y1)滑动到坐标(x2, y2),并返回是否成功。只有滑动操作执行完成时脚本才会继续执行。 */ function swipe(x1: number, y1: number, x2: number, y2: number, duration: number): boolean; type GesturePoint = [number, number]; /** * 模拟手势操作。例如gesture(1000, [0, 0], [500, 500], [500, 1000])为模拟一个从(0, 0)到(500, 500)到(500, 100)的手势操作,时长为2秒。 */ function gesture(duration: number, point1: GesturePoint, point2: GesturePoint, ...points: GesturePoint[]): void; type Gesture = [number, number, GesturePoint, GesturePoint] | [number, GesturePoint, GesturePoint]; /** * 同时模拟多个手势。每个手势的参数为[delay, duration, 坐标], delay为延迟多久(毫秒)才执行该手势;duration为手势执行时长;坐标为手势经过的点的坐标。其中delay参数可以省略,默认为0。 */ function gestures(gesture: Gesture, ...gestures: Gesture[]): void; /** * RootAutomator是一个使用root权限来模拟触摸的对象,用它可以完成触摸与多点触摸,并且这些动作的执行没有延迟。 * * 一个脚本中最好只存在一个RootAutomator,并且保证脚本结束退出他。 */ class RootAutomator { /** * 点击位置(x, y)。其中id是一个整数值,用于区分多点触摸,不同的id表示不同的"手指"。 */ tap(x: number, y: number, id?: number): void; /** * 模拟一次从(x1, y1)到(x2, y2)的时间为duration毫秒的滑动。 */ swipe(x1: number, x2: number, y1: number, y2: number, duration?: number): void; /** * 模拟按下位置(x, y),时长为duration毫秒。 */ press(x: number, y: number, duration: number, id?: number): void; /** * 模拟长按位置(x, y)。 */ longPress(x: number, y: number, duration?: number, id?: number): void; /** * 模拟手指按下位置(x, y)。 */ touchDown(x: number, y: number, id?: number): void; /** * 模拟移动手指到位置(x, y)。 */ touchMove(x: number, y: number, id?: number): void; /** * 模拟手指弹起。 */ touchUp(id?: number): void; } /** * 需要Root权限 * * 实验API,请勿过度依赖 * * 点击位置(x, y), 您可以通过"开发者选项"开启指针位置来确定点击坐标。 */ function Tap(x: number, y: number): void; /** * 需要Root权限 * * 实验API,请勿过度依赖 * * 滑动。从(x1, y1)位置滑动到(x2, y2)位置。 */ function Swipe(x1: number, x2: number, y1: number, y2: number, duration?: number): void; /** * device模块提供了与设备有关的信息与操作,例如获取设备宽高,内存使用率,IMEI,调整设备亮度、音量等。 * * 此模块的部分函数,例如调整音量,需要"修改系统设置"的权限。如果没有该权限,会抛出SecurityException并跳转到权限设置界面。 */ namespace device { /** * 设备屏幕分辨率宽度。例如1080。 */ var width: number; /** * 设备屏幕分辨率高度。例如1920。 */ var height: number; /** * 修订版本号,或者诸如"M4-rc20"的标识。 */ var buildId: string; /** * 设备的主板(?)名称。 */ var broad: string; /** * 与产品或硬件相关的厂商品牌,如"Xiaomi", "Huawei"等。 */ var brand: string; /** * 设备在工业设计中的名称(代号)。 */ var device: string; /** * 设备型号。 */ var model: string; /** * 整个产品的名称。 */ var product: string; /** * 设备Bootloader的版本。 */ var bootloader: string; /** * 设备的硬件名称(来自内核命令行或者/proc)。 */ var hardware: string; /** * 构建(build)的唯一标识码。 */ var fingerprint: string; /** * 硬件序列号。 */ var serial: string; /** * 安卓系统API版本。例如安卓4.4的sdkInt为19。 */ var sdkInt: number; /** * 设备固件版本号。 */ var incremental: string; /** * Android系统版本号。例如"5.0", "7.1.1"。 */ var release: string; /** * 基础操作系统。 */ var baseOS: string; /** * 安全补丁程序级别。 */ var securityPatch: string; /** * 开发代号,例如发行版是"REL"。 */ var codename: string; /** * 返回设备的IMEI。 */ function getIMEI(): string; /** * 返回设备的Android ID。 * * Android ID为一个用16进制字符串表示的64位整数,在设备第一次使用时随机生成,之后不会更改,除非恢复出厂设置。 */ function getAndroidId(): string; /** * 返回设备的Mac地址。该函数需要在有WLAN连接的情况下才能获取,否则会返回null。 * * 可能的后续修改:未来可能增加有root权限的情况下通过root权限获取,从而在没有WLAN连接的情况下也能返回正确的Mac地址,因此请勿使用此函数判断WLAN连接。 */ function getMacAddress(): string; /** * 返回当前的(手动)亮度。范围为0~255。 */ function getBrightness(): number; /** * 返回当前亮度模式,0为手动亮度,1为自动亮度。 */ function getBrightnessMode(): number; /** * 设置当前手动亮度。如果当前是自动亮度模式,该函数不会影响屏幕的亮度。 * * 此函数需要"修改系统设置"的权限。如果没有该权限,会抛出SecurityException并跳转到权限设置界面。 */ function setBrightness(b: number): void; /** * 设置当前亮度模式。 * * 此函数需要"修改系统设置"的权限。如果没有该权限,会抛出SecurityException并跳转到权限设置界面。 */ function setBrightnessMode(mode: 0 | 1): void; /** * 返回当前媒体音量。 */ function getMusicVolume(): number; /** * 返回当前通知音量。 */ function getNotificationVolume(): number; /** * 返回当前闹钟音量。 */ function getAlarmVolume(): number; /** * 返回媒体音量的最大值。 */ function getMusicMaxVolume(): number; /** * 返回通知音量的最大值。 */ function getNotificationMaxVolume(): number; /** * 返回闹钟音量的最大值。 */ function getAlarmMaxVolume(): number; /** * 设置当前媒体音量。 * * 此函数需要"修改系统设置"的权限。如果没有该权限,会抛出SecurityException并跳转到权限设置界面。 */ function setMusicVolume(volume: number): void; /** * 设置当前通知音量。 * * 此函数需要"修改系统设置"的权限。如果没有该权限,会抛出SecurityException并跳转到权限设置界面。 */ function setNotificationVolume(volume: number): void; /** * 设置当前闹钟音量。 * * 此函数需要"修改系统设置"的权限。如果没有该权限,会抛出SecurityException并跳转到权限设置界面。 */ function setAlarmVolume(volume: number): void; /** * 返回当前电量百分比。 */ function getBattery(): number; /** * 返回设备是否正在充电。 */ function isCharging(): boolean; /** * 返回设备内存总量,单位字节(B)。1MB = 1024 * 1024B。 */ function getTotalMem(): number; /** * 返回设备当前可用的内存,单位字节(B)。 */ function getAvailMem(): number; /** * 返回设备屏幕是否是亮着的。如果屏幕亮着,返回true; 否则返回false。 * * 需要注意的是,类似于vivo xplay系列的息屏时钟不属于"屏幕亮着"的情况,虽然屏幕确实亮着但只能显示时钟而且不可交互,此时isScreenOn()也会返回false。 */ function isScreenOn(): boolean; /** * 唤醒设备。包括唤醒设备CPU、屏幕等。可以用来点亮屏幕。 */ function wakeUp(): void; /** * 如果屏幕没有点亮,则唤醒设备。 */ function wakeUpIfNeeded(): void; /** * 保持屏幕常亮。 * * 此函数无法阻止用户使用锁屏键等正常关闭屏幕,只能使得设备在无人操作的情况下保持屏幕常亮;同时,如果此函数调用时屏幕没有点亮,则会唤醒屏幕。 * * 在某些设备上,如果不加参数timeout,只能在Auto.js的界面保持屏幕常亮,在其他界面会自动失效,这是因为设备的省电策略造成的。因此,建议使用比较长的时长来代替"一直保持屏幕常亮"的功能,例如device.keepScreenOn(3600 * 1000)。 * * 可以使用device.cancelKeepingAwake()来取消屏幕常亮。 */ function keepScreenOn(timeout: number): void; /** * 保持屏幕常亮,但允许屏幕变暗来节省电量。此函数可以用于定时脚本唤醒屏幕操作,不需要用户观看屏幕,可以让屏幕变暗来节省电量。 * * 此函数无法阻止用户使用锁屏键等正常关闭屏幕,只能使得设备在无人操作的情况下保持屏幕常亮;同时,如果此函数调用时屏幕没有点亮,则会唤醒屏幕。 * * 可以使用device.cancelKeepingAwake()来取消屏幕常亮。 */ function keepScreenDim(timeout: number): void; /** * 取消设备保持唤醒状态。用于取消device.keepScreenOn(), device.keepScreenDim()等函数设置的屏幕常亮。 */ function cancelKeepingAwake(): void; /** * 使设备震动一段时间。 */ function vibrate(millis: number): void; /** * 如果设备处于震动状态,则取消震动。 */ function cancelVibration(): void; } /** * dialogs 模块提供了简单的对话框支持,可以通过对话框和用户进行交互。 */ namespace dialogs { /** * 显示一个只包含“确定”按钮的提示对话框。直至用户点击确定脚本才继续运行。 */ function alert(title: string, content?: string): void; /** * UI模式 * * 显示一个只包含“确定”按钮的提示对话框。直至用户点击确定脚本才继续运行。 */ function alert(title: string, content?: string, callback?: () => void): Promise<void>; /** * 显示一个包含“确定”和“取消”按钮的提示对话框。如果用户点击“确定”则返回 true ,否则返回 false 。 */ function confirm(title: string, content?: string): boolean; /** * UI模式 * * 显示一个包含“确定”和“取消”按钮的提示对话框。如果用户点击“确定”则返回 true ,否则返回 false 。 */ function confirm(title: string, content?: string, callback?: (value: boolean) => void): Promise<boolean>; /** * 显示一个包含输入框的对话框,等待用户输入内容,并在用户点击确定时将输入的字符串返回。如果用户取消了输入,返回null。 */ function rawInput(title: string, prefill?: string): string; /** * UI模式 * * 显示一个包含输入框的对话框,等待用户输入内容,并在用户点击确定时将输入的字符串返回。如果用户取消了输入,返回null。 */ function rawInput(title: string, prefill?: string, callback?: (value: string) => void): Promise<string>; /** * 等效于 eval(dialogs.rawInput(title, prefill, callback)), 该函数和rawInput的区别在于,会把输入的字符串用eval计算一遍再返回,返回的可能不是字符串。 */ function input(title: string, prefill?: string): any; /** * UI模式 * * 等效于 eval(dialogs.rawInput(title, prefill, callback)), 该函数和rawInput的区别在于,会把输入的字符串用eval计算一遍再返回,返回的可能不是字符串。 */ function input(title: string, prefill?: string, callback?: (value: any) => void): Promise<any>; /** * 显示一个包含输入框的对话框,等待用户输入内容,并在用户点击确定时将输入的字符串返回。如果用户取消了输入,返回null。 */ function prompt(title: string, prefill?: string): string; /** * UI模式 * * 显示一个包含输入框的对话框,等待用户输入内容,并在用户点击确定时将输入的字符串返回。如果用户取消了输入,返回null。 */ function prompt(title: string, prefill?: string, callback?: (value: string) => void): Promise<string>; /** * 显示一个带有选项列表的对话框,等待用户选择,返回用户选择的选项索引(0 ~ item.length - 1)。如果用户取消了选择,返回-1。 */ function select(title: string, items: string[]): number; /** * UI模式 * * 显示一个带有选项列表的对话框,等待用户选择,返回用户选择的选项索引(0 ~ item.length - 1)。如果用户取消了选择,返回-1。 */ function select(title: string, items: string[], callback?: (value: number) => void): Promise<number>; /** * 显示一个单选列表对话框,等待用户选择,返回用户选择的选项索引(0 ~ item.length - 1)。如果用户取消了选择,返回-1。 */ function singleChoice(title: string, items: string[], index?: number): number; /** * UI模式 * * 显示一个单选列表对话框,等待用户选择,返回用户选择的选项索引(0 ~ item.length - 1)。如果用户取消了选择,返回-1。 */ function singleChoice(title: string, items: string[], index?: number, callback?: (choice: number) => void): Promise<number>; /** * 显示一个多选列表对话框,等待用户选择,返回用户选择的选项索引的数组。如果用户取消了选择,返回[]。 */ function multiChoice(title: string, items: string[], indices?: number[]): number[]; /** * UI模式 * * 显示一个多选列表对话框,等待用户选择,返回用户选择的选项索引的数组。如果用户取消了选择,返回[]。 */ function multiChoice(title: string, items: string[], indices?: number[], callback?: (choices: number[]) => void): Promise<number[]>; } /** * 显示一个只包含“确定”按钮的提示对话框。直至用户点击确定脚本才继续运行。 */ function alert(title: string, content?: string): void; /** * UI模式 * * 显示一个只包含“确定”按钮的提示对话框。直至用户点击确定脚本才继续运行。 * * 在ui模式下该函数返回一个Promise。 */ function alert(title: string, content?: string, callback?: () => void): Promise<void>; /** * 显示一个包含“确定”和“取消”按钮的提示对话框。如果用户点击“确定”则返回 true ,否则返回 false 。 */ function confirm(title: string, content?: string): boolean; /** * UI模式 * * 显示一个包含“确定”和“取消”按钮的提示对话框。如果用户点击“确定”则返回 true ,否则返回 false 。 * * 在ui模式下该函数返回一个Promise。 */ function confirm(title: string, content?: string, callback?: (value: boolean) => void): Promise<boolean>; /** * 显示一个包含输入框的对话框,等待用户输入内容,并在用户点击确定时将输入的字符串返回。如果用户取消了输入,返回null。 */ function rawInput(title: string, prefill?: string): string; /** * UI模式 * * 显示一个包含输入框的对话框,等待用户输入内容,并在用户点击确定时将输入的字符串返回。如果用户取消了输入,返回null。 */ function rawInput(title: string, prefill?: string, callback?: (value: string) => void): Promise<string>; /** * engines模块包含了一些与脚本环境、脚本运行、脚本引擎有关的函数,包括运行其他脚本,关闭脚本等。 */ namespace engines { /** * 脚本引擎对象。 */ interface ScriptEngine { /** * 停止脚本引擎的执行。 */ forceStop(): void; /** * 返回脚本执行的路径。对于一个脚本文件而言为这个脚本所在的文件夹;对于其他脚本,例如字符串脚本,则为null或者执行时的设置值。 */ cwd(): string; } /** * 执行脚本时返回的对象,可以通过他获取执行的引擎、配置等,也可以停止这个执行。 * * 要停止这个脚本的执行,使用exectuion.getEngine().forceStop(). */ interface ScriptExecution { /** * 返回执行该脚本的脚本引擎对象(ScriptEngine) */ getEngine(): ScriptEngine; /** * 返回该脚本的运行配置(ScriptConfig) */ getConfig(): ScriptConfig; } /** * 运行配置项。 */ interface ScriptConfig { /** * 延迟执行的毫秒数,默认为0。 */ delay?: number; /** * 循环运行次数,默认为1。0为无限循环。 */ loopTimes?: number; /** * 循环运行时两次运行之间的时间间隔,默认为0。 */ interval?: number; /** * 指定脚本运行的目录。这些路径会用于require时寻找模块文件。 */ path?: string | string[]; /** * 返回一个字符串数组表示脚本运行时模块寻找的路径。 */ getpath?: string[]; } /** * 在新的脚本环境中运行脚本script。返回一个ScriptExectuion对象。 * * 所谓新的脚本环境,指定是,脚本中的变量和原脚本的变量是不共享的,并且,脚本会在新的线程中运行。 */ function execScript(name: string, script: string, config?: ScriptConfig): ScriptExecution; /** * 在新的脚本环境中运行脚本文件path:string。返回一个ScriptExecution对象。 */ function execScriptFile(path: string, config?: ScriptConfig): ScriptExecution; /** * 在新的脚本环境中运行录制文件path:string。返回一个ScriptExecution对象。 */ function execAutoFile(path: string, config?: ScriptConfig): ScriptExecution; /** * 停止所有正在运行的脚本。包括当前脚本自身。 */ function stopAll(): void; /** * 停止所有正在运行的脚本并显示停止的脚本数量。包括当前脚本自身。 */ function stopAllAndToast(): void; /** * 返回当前脚本的脚本引擎对象(ScriptEngine) */ function myEngine(): void; } namespace events { interface KeyEvent { getAction(); getKeyCode(): number; getEventTime(): number; getDownTime(): number; keyCodeToString(keyCode: number): string; } function emitter(): EventEmitter; function observeKey(): void; type Keys = 'volume_up' | 'volume_down' | 'home' | 'back' | 'menu'; function setKeyInterceptionEnabled(key: Keys, enabled: boolean); function setKeyInterceptionEnabled(enabled: boolean); function onKeyDown(keyName: Keys, listener: (e: KeyEvent) => void): void; function onceKeyUp(keyName: Keys, listener: (e: KeyEvent) => void): void; function removeAllKeyDownListeners(keyName: Keys): void; function removeAllKeyUpListeners(keyName: Keys): void; function observeTouch(): void; function setTouchEventTimeout(timeout: number): void; function getTouchEventTimeout(): number; function onTouch(listener: (point: Point) => void): void; function removeAllTouchListeners(): void; function on(event: 'key' | 'key_down' | 'key_up', listener: (keyCode: number, e: KeyEvent) => void): void; function on(event: 'exit', listener: () => void): void; function observeNotification(): void; function observeToast(): void; /** * 系统Toast对象 */ interface Toast { /** * 获取Toast的文本内容 */ getText(): string; /** * 获取发出Toast的应用包名 */ getPackageName(): void; } function onToast(listener: (toast: Toast) => void): void; /** * 通知对象,可以获取通知详情,包括通知标题、内容、发出通知的包名、时间等,也可以对通知进行操作,比如点击、删除。 */ interface Notification { number: number; when: number; getPackageName(): string; getTitle(): string; getText(): string; click(): void; delete(): void; } function on(event: 'notification', listener: (notification: Notification) => void): void; } /** * 按键事件中所有可用的按键名称 */ enum keys { home, back, menu, volume_up, volume_down } interface EventEmitter { defaultMaxListeners: number; addListener(eventName: string, listener: (...args: any[]) => void): EventEmitter; emit(eventName: string, ...args: any[]): boolean; eventNames(): string[]; getMaxListeners(): number; listenerCount(eventName: string): number; on(eventName: string, listener: (...args: any[]) => void): EventEmitter; once(eventName: string, listener: (...args: any[]) => void): EventEmitter; prependListener(eventName: string, listener: (...args: any[]) => void): EventEmitter; prependOnceListener(eventName: string, listener: (...args: any[]) => void): EventEmitter; removeAllListeners(eventName?: string): EventEmitter; removeListener(eventName: string, listener: (...args: any[]) => void): EventEmitter; setMaxListeners(n: number): EventEmitter; } namespace floaty { function window(layout: any): FloatyWindow; function closeAll(): void; interface FloatyWindow { setAdjustEnabled(enabled: boolean): void; setPosition(x: number, y: number): void; getX(): number; getY(): number; setSize(width: number, height: number): void; getWidht(): number; getHeight(): number; close(): void; exitOnClose(): void; } } namespace files { type byte = number; function isFile(path: string): boolean; function isDir(path: string): boolean; function isEmptyDir(path: string): boolean; function join(parent: string, ...child: string[]): string; function create(path: string): boolean; function createWithDirs(path: string): boolean; function exists(path: string): boolean; function ensureDir(path: string): void; function read(path: string, encoding?: string): string; function readBytes(path: string): byte[]; function write(path: string, text, encoding?: string): void; function writeBytes(path: string, bytes: byte[]): void; function append(path: string, text: string, encoding?: string): void; function appendBytes(path: string, text: byte[], encoding?: string): void; function copy(frompath: string, topath: string): boolean; function move(frompath: string, topath: string): boolean; function rename(path: string, newName): boolean; function renameWithoutExtension(path: string, newName: string): boolean; function getName(path: string): string; function getNameWithoutExtension(path: string): string; function getExtension(path: string): string; function remove(path: string): boolean; function removeDir(path: string): boolean; function getSdcardPath(): string; function cwd(): string; function path(relativePath: string): string; function listDir(path: string, filter: (filename: string) => boolean): string[]; } interface ReadableTextFile { read(): string; read(maxCount: number): string; readline(): string; readlines(): string[]; close(): void; } interface WritableTextFile { write(text: string): void; writeline(line: string): void; writelines(lines: string[]): void; flush(): void; close(): void; } function open(path: string, mode?: 'r', encoding?: string, bufferSize?: number): ReadableTextFile; function open(path: string, mode?: 'w' | 'a', encoding?: string, bufferSize?: number): WritableTextFile; namespace media { function scanFile(path: string): void; function playMusic(path: string, volume?: number, looping?: boolean); function musicSeekTo(msec: number): void; function pauseMusic(): void; function resumeMusic(): void; function stopMusic(): void; function isMusicPlaying(): boolean; function getMusicDuration(): number; function getMusicCurrentPosition(): number; } namespace sensors { interface SensorEventEmitter { on(eventName: 'change', callback: (...args: number[]) => void): void; on(eventName: 'accuracy_change', callback: (accuracy: number) => void): void; } function on(eventName: 'unsupported_sensor', callback: (sensorName: string) => void): void; function register(sensorName: string, delay?: delay): SensorEventEmitter; function unregister(emitter: SensorEventEmitter); function unregisterAll(): void; var ignoresUnsupportedSensor: boolean; enum delay { normal, ui, game, fastest } } function sleep(n: number): void; function currentPackage(): string; function currentActivity(): string; function setClip(test: string): void; function getClip(): string; function toast(message: string): void; function toastLog(message: string): void; function waitForActivity(activity: string, period?: number): void; function waitForPackage(packageName: string, period?: number): void; function exit(): void; function random(): number; function random(min: number, max: number): number; namespace http { interface HttpRequestOptions { header: { [key: string]: string }, method: 'GET' | 'POST' | 'PUT' | 'DELET' | 'PATCH'; contentType: string; body: string | string[] | files.byte[] } interface Request { } interface Response { statusCode: number; statusMessage: string; headers: { [key: string]: string }; body: ResponseBody; request: Request; url: string; method: 'GET' | 'POST' | 'PUT' | 'DELET' | 'PATCH'; } interface ResponseBody { bytes(): files.byte[]; string(): string; json(): object; contentType: string; } function get(url: string, options?: HttpRequestOptions, callback?: (resp: Response) => void): Response; function post(url: string, data: object, options?: HttpRequestOptions, callback?: (resp: Response) => void): Response; function postJson(url: string, data?: object, options?: HttpRequestOptions, callback?: (resp: Response) => void): Response; interface RequestMultipartBody { file: ReadableTextFile | [string, string] | [string, string, string]; } function postMultipart(url: string, files: RequestMultipartBody, options?: HttpRequestOptions, callback?: (resp: Response) => void): void; function postMultipart(url: string, files: { [key: string]: string } & RequestMultipartBody, options?: HttpRequestOptions, callback?: (resp: Response) => void): void; function request(url: string, options?: HttpRequestOptions, callback?: (resp: Response) => void): void; } interface Image { getWidth(): number; getHeight(): number; saveTo(path: string): void; pixel(x: number, y: number): number; } namespace images { function requestScreenCapture(landscape?: boolean): boolean; function captureScreen(): Image; function captureScreen(path: string): void; function pixel(image: Image, x: number, y: number): number; function save(image: Image, path: string): void; function read(path: string): Image; function load(url: string): Image; interface FindColorOptions { region?: [number, number] | [number, number, number, number]; threshold?: number; } function clip(image: Image, x: number, y: number, w: number, h: number): Image; function findColor(image: Image, color: number | string, options: FindColorOptions): Point; function findColorInRegion(image: Image, color: number | string, x: number, y: number, width?: number, height?: number, threshold?: number): Point; function findColorEquals(image: Image, color: number | string, x?: number, y?: number, width?: number, height?: number): Point; function detectsColor(image: Image, color: number | string, x: number, y: number, threshold?: number, algorithm?: 'diff'): Point; interface FindImageOptions { region?: [number, number] | [number, number, number, number]; threshold?: number; level?: number; } function findImage(image: Image, template: Image, options?: FindImageOptions): Point; function findImageInRegion(image: Image, template: Image, x: number, y: number, width?: number, height?: number, threshold?: number): Point; function findMultiColors(image: Image, firstColor: number | string, colors: [number, number, number | string][], options?: FindColorOptions): Point; } namespace colors { function toString(color: number): string; function red(color: number | string): number; function green(color: number | string): number; function blue(color: number | string): number; function alpha(color: number | string): number; function rgb(red: number, green: number, blue: number): number; function argb(alpha: number, red: number, green: number, blue: number): number; function parseColor(colorStr: string): number; function isSimilar(color1: number | string, color2: number | string, threshold: number, algorithm: 'diff' | 'rgb' | 'rgb+' | 'hs'): boolean; function equals(color1: number | string, color2: number | string): boolean; } /* 全局按键 */ function back(): boolean; function home(): boolean; function powerDialog(): boolean; function notifications(): boolean; function quickSettings(): boolean; function recents(): boolean; function splitScreen(): boolean; function Home(): void; function Back(): void; function Power(): void; function Menu(): void; function VolumeUp(): void; function VolumeDown(): void; function Camera(): void; function Up(): void; function Down(): void; function Left(): void; function Right(): void; function OK(): void; function Text(text: string): void; function KeyCode(code: number | string): void; // var module: { exports: any }; interface Storage { get<T>(key: string, defaultValue?: T): T; put<T>(key: string, value: T): void; remove(key: string): void; contains(key: string): boolean; clear(): void; } namespace storages { function create(name: string): Storage; function remove(name: string): boolean; } function auto(mode?: 'fast' | 'normal'): void; namespace auto { function waitFor(): void; function setMode(mode: 'fast' | 'normal'): void; } function selector(): UiSelector; function click(text: string, index?: number): boolean; function click(left: number, top: number, bottom: number, right: number): boolean; function longClick(text: string, index?: number): boolean; function scrollUp(index?: number): boolean; function scrollDown(index?: number): boolean; function setText(text: string): boolean; function setText(index: number, text: string): boolean; function input(text: string): boolean; function input(index: number, text: string): boolean; interface UiSelector { text(str: string): UiSelector; textContains(str: string): UiSelector; textStartsWith(prefix: string): UiSelector; textEndsWith(suffix: string): UiSelector; textMatches(reg: string | RegExp): UiSelector; desc(str: string): UiSelector; descContains(str: string): UiSelector; descStartsWith(prefix: string): UiSelector; descEndsWith(suffix: string): UiSelector; descMatches(reg: string | RegExp): UiSelector; id(resId: string): UiSelector; idContains(str: string): UiSelector; idStartsWith(prefix: string): UiSelector; idEndsWith(suffix: string): UiSelector; idMatches(reg: string | RegExp): UiSelector; className(str: string): UiSelector; classNameContains(str: string): UiSelector; classNameStartsWith(prefix: string): UiSelector; classNameEndsWith(suffix: string): UiSelector; classNameMatches(reg: string | RegExp): UiSelector; packageName(str: string): UiSelector; packageNameContains(str: string): UiSelector; packageNameStartsWith(prefix: string): UiSelector; packageNameEndsWith(suffix: string): UiSelector; packageNameMatches(reg: string | RegExp): UiSelector; bounds(left: number, top: number, right: number, buttom: number): UiSelector; boundsInside(left: number, top: number, right: number, buttom: number): UiSelector; boundsContains(left: number, top: number, right: number, buttom: number): UiSelector; drawingOrder(order): UiSelector; clickable(b: boolean): UiSelector; longClickable(b: boolean): UiSelector; checkable(b: boolean): UiSelector; selected(b: boolean): UiSelector; enabled(b: boolean): UiSelector; scrollable(b: boolean): UiSelector; editable(b: boolean): UiSelector; multiLine(b: boolean): UiSelector; findOne(): UiObject; findOne(timeout: number): UiObject; findOnce(): UiObject; findOnce(i: number): UiObject; find(): UiCollection; untilFind(): UiCollection; exists(): boolean; waitFor(): void; filter(filter: (obj: UiObject) => boolean) } interface UiObject { click(): boolean; longClick(): boolean; setText(text: string): boolean; copy(): boolean; cut(): boolean; paste(): boolean; setSelection(start, end): boolean; scrollForward(): boolean; scrollBackward(): boolean; select(): boolean; collapse(): boolean; expand(): boolean; show(): boolean; scrollUp(): boolean; scrollDown(): boolean; scrollLeft(): boolean; scrollRight(): boolean; children(): UiCollection; childCount(): number; child(i: number): UiObject; parent(): UiObject; bounds(): Rect; boundsInParent(): Rect; drawingOrder(): number; id(): string; text(): string; findByText(str: string): UiCollection; findOne(selector): UiObject; find(selector): UiCollection; } interface UiCollection { size(): number; get(i: number): UiObject; each(func: (obj: UiObject) => void): void; empty(): boolean; nonEmpty(): boolean; find(selector): UiCollection; findOne(selector): UiObject; } interface Rect { left: number; right: number; top: number; bottom: number; centerX(): number; centerY(): number; width(): number; height(): number; contains(r): Rect; intersect(r): Rect; } } export { };
the_stack
import { Plan } from '@prisma/client' import * as t from 'io-ts' import { PathReporter } from 'io-ts/lib/PathReporter' import yaml from 'js-yaml' import ml from 'multilines' import * as os from 'os' import { mapEntries, mapKeys } from './data/dict' import { withDefault } from './utils' /* Constants */ const NUMBER_OF_FREE_TIERS = 5 /** * Configuration repository is the repository which LabelSync * uses to determine the configuration of the service. */ export const getLSConfigRepoName = (account: string) => `${account.toLowerCase()}-labelsync` /** * Configuration file path determines the path of the file in the repositoy * that we use to gather configuration information from. * * It should always be in YAML format. */ export const LS_CONFIG_PATH = 'labelsync.yml' /** * Label represents the central unit of LabelSync. Each label * can have multiple siblings that are meaningfully related to * a label itself, multiple hooks that trigger different actions. */ const LSCLabel = t.intersection([ t.type({ color: t.string, }), t.partial({ description: t.string, siblings: t.array(t.string), alias: t.array(t.string), }), ]) export type LSCLabel = t.TypeOf<typeof LSCLabel> const LSCLabelName = t.string export type LSCLabelName = t.TypeOf<typeof LSCLabelName> /** * Repository configuration for how LabelSync should sync it. */ const LSCRepositoryConfiguration = t.partial({ removeUnconfiguredLabels: t.boolean, }) export interface LSCRepositoryConfiguration extends t.TypeOf<typeof LSCRepositoryConfiguration> {} /** * Repository represents a single Github repository. * When configured as `strict` it will delete any surplus of labels * in the repository. */ const LSCRepository = t.intersection([ t.partial({ config: LSCRepositoryConfiguration, }), t.type({ labels: t.record(LSCLabelName, LSCLabel), }), ]) export interface LSCRepository extends t.TypeOf<typeof LSCRepository> {} const LSCRepositoryName = t.string export type LSCRepositoryName = t.TypeOf<typeof LSCRepositoryName> /** * Configuration represents an entire configuration for all * LabelSync tools that an organisation is using. */ const LSCConfiguration = t.type({ repos: t.record(LSCRepositoryName, LSCRepository), }) export interface LSCConfiguration extends t.TypeOf<typeof LSCConfiguration> {} /** * Parses a string into a configuration object. */ export function parseConfig( plan: Plan, input: string, logger?: (err: any) => any, ): [string] | [null, LSCConfiguration] { try { const object = yaml.safeLoad(input) const config = LSCConfiguration.decode(object) if (config._tag === 'Left') { return [PathReporter.report(config).join(os.EOL)] } /* Perform checks on the content */ const parsedConfig = checkPurchase( plan, validateCongiuration(fixConfig(config.right)), ) return [null, parsedConfig] } catch (err) /* istanbul ignore next */ { if (logger) logger(err) return [err.message] } } /* PLAN LIMITATIONS */ /** * Makes sure that none of LabelSync limitations appears in the cofnig. */ function checkPurchase(plan: Plan, config: LSCConfiguration): LSCConfiguration { /* Data */ const numberOfConfiguredRepos = Object.keys(config.repos).length switch (plan) { case 'FREE': { /* FREE */ /** * Report too many configurations. */ if (numberOfConfiguredRepos >= NUMBER_OF_FREE_TIERS) { const report = ml` | You are trying to configure more repositories than there are available in your plan. | Update your current plan to access all the features LabelSync offers. ` throw new Error(report) } /** * Report wildcard configuration. */ if (Object.keys(config.repos).includes('*')) { const report = ml` | You are trying to configure a wildcard configuration on a free plan. | Update your current plan to access all the features LabelSync offers. ` throw new Error(report) } return config } case 'PAID': { /* No limits for purchased accounts. */ return config } } } /* CONTENT CHECK */ /** * Returns configuration if everything seems as expected. Throws otherwise * with the error exaplanation. */ function validateCongiuration(config: LSCConfiguration): LSCConfiguration { /** * We accumulate possible errors in all the checks and throw the collection. */ let errors: string[] = [] /* MISSING SIBLINGS */ /** * All siblings should be defined in the configuration. */ let missingSiblings: { repo: string; sibling: string; label: string }[] = [] for (const repoName in config.repos) { const repoConfig = config.repos[repoName] const configuredLabels = Object.keys(repoConfig.labels) /* Check every label for unconfigured siblings. */ for (const label in repoConfig.labels) { const siblings = withDefault([], repoConfig.labels[label].siblings) for (const sibling of siblings) { /* Report unconfigured missing sibling. */ if (!configuredLabels.includes(sibling)) { missingSiblings.push({ repo: repoName, sibling, label }) } } } } if (missingSiblings.length !== 0) { const report = ml` | Configuration references unconfigured siblings: | ${missingSiblings .map((s) => `* \`${s.sibling}\` in ${s.repo}:${s.label}`) .join(os.EOL)} ` errors.push(report) } /* ALIAS SPLITING */ /** * You shouldn't make two new labels aliasing one label. */ let duplicateAliaii: { repo: string; alias: string; labels: string[] }[] = [] /* Check each repository */ for (const repoName in config.repos) { const repoConfig = config.repos[repoName] let aliaiiInRepo: { [alias: string]: string[] } = {} /* Check every label for unconfigured siblings. */ for (const label in repoConfig.labels) { const aliaii = withDefault([], repoConfig.labels[label].alias) /* Create a map of aliases. */ for (const alias of aliaii) { if (!aliaiiInRepo.hasOwnProperty(alias)) aliaiiInRepo[alias] = [] aliaiiInRepo[alias].push(label) } } /* Find multiples */ for (const alias in aliaiiInRepo) { if (aliaiiInRepo[alias].length > 1) { duplicateAliaii.push({ repo: repoName, alias, labels: aliaiiInRepo[alias], }) } } } if (duplicateAliaii.length !== 0) { const report = ml` | Configuration references same old label twice in alias: | ${duplicateAliaii .map( (s) => `* \`${s.alias}\` appears in ${s.repo}:${s.labels.join(', ')}`, ) .join(os.EOL)} | | Each legacy label may only be referenced once in alias. ` errors.push(report) } /* SELF REFERENCES */ /** * Siblings shouldn't self-reference themselves. */ let selfreferencingSiblings: { repo: string; label: string }[] = [] for (const repoName in config.repos) { const repoConfig = config.repos[repoName] /** * Check every label if it references itself. */ for (const label in repoConfig.labels) { const siblings = withDefault([], repoConfig.labels[label].siblings) if (siblings.includes(label)) { selfreferencingSiblings.push({ repo: repoName, label }) } } } if (selfreferencingSiblings.length !== 0) { const report = ml` | Some of the labels in the configuration reference itself as a sibling: | ${selfreferencingSiblings .map((s) => `* \`${s.label}\` in ${s.repo}`) .join(os.EOL)} ` errors.push(report) } /* DESCRIPTION LENGTHS */ /** * Siblings shouldn't self-reference themselves. */ let labelsWithTooLongDescriptions: { repo: string; label: string }[] = [] for (const repoName in config.repos) { const repoConfig = config.repos[repoName] /** * Check every label if it references itself. */ for (const label in repoConfig.labels) { const { description } = repoConfig.labels[label] if (description && description.length > 1000) { labelsWithTooLongDescriptions.push({ repo: repoName, label }) } } } if (labelsWithTooLongDescriptions.length !== 0) { const report = ml` | Some of the labels in the configuration have too long descriptions: | ${selfreferencingSiblings .map((s) => `* \`${s.label}\` in ${s.repo}`) .join(os.EOL)} | The maximum is 1000 characters. ` errors.push(report) } /** * Collect the errors and throw if necessary. */ if (errors.length > 0) { const report = errors.join(os.EOL) throw new Error(report) } return config } /** * TRANSFORMATIONS */ /** * Catches configuration issues that io-ts couldn't catch. */ function fixConfig(config: LSCConfiguration): LSCConfiguration { const repos = mapEntries(config.repos, fixRepoConfig) const lowercaseRepos = mapKeys(repos, (repo) => repo.toLowerCase()) return { ...config, repos: lowercaseRepos, } } /** * Fixes issues that io-ts couldn't catch. */ function fixRepoConfig(config: LSCRepository): LSCRepository { const labels = mapEntries<LSCLabel, LSCLabel>(config.labels, (label) => ({ ...label, color: fixLabelColor(label.color), })) return { ...config, labels, } } /** * Removes hash from the color. */ export function fixLabelColor(color: string): string { if (color.startsWith('#')) return color.slice(1).toLowerCase() return color.toLowerCase() } /** * Returns a list of repositories in configuration without wildcard config. */ export function configRepos(config: LSCConfiguration): string[] { return Object.keys(config.repos).filter((repo) => repo !== '*') } /** * Tells whether the repository is the configuration * repository for the account. */ export function isConfigRepo(account: string, repo: string): boolean { return getLSConfigRepoName(account) === repo.toLowerCase() }
the_stack
import {fireEvent, render, screen, cleanup} from '@testing-library/react'; import {useRef, useState} from 'react'; import { useListNavigation, useFloating, useInteractions, useClick, } from '../../src'; import type {Props} from '../../src/hooks/useListNavigation'; function App(props: Omit<Partial<Props>, 'listRef'>) { const [open, setOpen] = useState(false); const listRef = useRef<Array<HTMLLIElement | null>>([]); const [activeIndex, setActiveIndex] = useState<null | number>(null); const {reference, floating, context} = useFloating({ open, onOpenChange: setOpen, }); const {getReferenceProps, getFloatingProps, getItemProps} = useInteractions([ useClick(context), useListNavigation(context, { ...props, listRef, activeIndex, onNavigate(index) { setActiveIndex(index); props.onNavigate?.(index); }, }), ]); return ( <> <button {...getReferenceProps({ref: reference})} /> {open && ( <div role="menu" {...getFloatingProps({ref: floating})}> <ul> {['one', 'two', 'three'].map((string, index) => ( <li data-testid={`item-${index}`} aria-selected={activeIndex === index} key={string} tabIndex={-1} {...getItemProps({ ref(node: HTMLLIElement) { listRef.current[index] = node; }, })} > {string} </li> ))} </ul> </div> )} </> ); } test('opens on ArrowDown and focuses first item', () => { render(<App />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.getByRole('menu')).toBeInTheDocument(); expect(screen.getByTestId('item-0')).toHaveFocus(); cleanup(); }); test('opens on ArrowUp and focuses last item', async () => { render(<App />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowUp'}); expect(screen.queryByRole('menu')).toBeInTheDocument(); expect(screen.getByTestId('item-2')).toHaveFocus(); cleanup(); }); test('navigates down on ArrowDown', async () => { render(<App />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.queryByRole('menu')).toBeInTheDocument(); expect(screen.getByTestId('item-0')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-1')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-2')).toHaveFocus(); // Reached the end of the list. fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-2')).toHaveFocus(); cleanup(); }); test('navigates up on ArrowUp', async () => { render(<App />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowUp'}); expect(screen.queryByRole('menu')).toBeInTheDocument(); expect(screen.getByTestId('item-2')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowUp'}); expect(screen.getByTestId('item-1')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowUp'}); expect(screen.getByTestId('item-0')).toHaveFocus(); // Reached the end of the list. fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowUp'}); expect(screen.getByTestId('item-0')).toHaveFocus(); cleanup(); }); describe('loop', () => { test('ArrowDown looping', () => { render(<App loop />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.queryByRole('menu')).toBeInTheDocument(); expect(screen.getByTestId('item-0')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-1')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-2')).toHaveFocus(); // Reached the end of the list and loops. fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-0')).toHaveFocus(); cleanup(); }); test('ArrowUp looping', () => { render(<App loop />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowUp'}); expect(screen.queryByRole('menu')).toBeInTheDocument(); expect(screen.getByTestId('item-2')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowUp'}); expect(screen.getByTestId('item-1')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowUp'}); expect(screen.getByTestId('item-0')).toHaveFocus(); // Reached the end of the list and loops. fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowUp'}); expect(screen.getByTestId('item-2')).toHaveFocus(); cleanup(); }); }); describe('orientation', () => { test('navigates down on ArrowDown', async () => { render(<App orientation="horizontal" />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowRight'}); expect(screen.queryByRole('menu')).toBeInTheDocument(); expect(screen.getByTestId('item-0')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowRight'}); expect(screen.getByTestId('item-1')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowRight'}); expect(screen.getByTestId('item-2')).toHaveFocus(); // Reached the end of the list. fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowRight'}); expect(screen.getByTestId('item-2')).toHaveFocus(); cleanup(); }); test('navigates up on ArrowLeft', async () => { render(<App orientation="horizontal" />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowLeft'}); expect(screen.queryByRole('menu')).toBeInTheDocument(); expect(screen.getByTestId('item-2')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowLeft'}); expect(screen.getByTestId('item-1')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowLeft'}); expect(screen.getByTestId('item-0')).toHaveFocus(); // Reached the end of the list. fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowLeft'}); expect(screen.getByTestId('item-0')).toHaveFocus(); cleanup(); }); }); describe('focusItemOnOpen', () => { test('true click', () => { render(<App focusItemOnOpen={true} />); fireEvent.click(screen.getByRole('button')); expect(screen.getByTestId('item-0')).toHaveFocus(); cleanup(); }); test('false click', () => { render(<App focusItemOnOpen={false} />); fireEvent.click(screen.getByRole('button')); expect(screen.getByTestId('item-0')).not.toHaveFocus(); cleanup(); }); }); describe('allowEscape + virtual', () => { test('true', () => { render(<App allowEscape={true} virtual loop />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-0').getAttribute('aria-selected')).toBe( 'true' ); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowUp'}); expect(screen.getByTestId('item-0').getAttribute('aria-selected')).toBe( 'false' ); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-0').getAttribute('aria-selected')).toBe( 'true' ); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-1').getAttribute('aria-selected')).toBe( 'true' ); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-2').getAttribute('aria-selected')).toBe( 'true' ); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-2').getAttribute('aria-selected')).toBe( 'false' ); cleanup(); }); test('false', () => { render(<App allowEscape={false} virtual loop />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-0').getAttribute('aria-selected')).toBe( 'true' ); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-1').getAttribute('aria-selected')).toBe( 'true' ); cleanup(); }); test('true - onNavigate is called with `null` when escaped', () => { const spy = jest.fn(); render(<App allowEscape virtual loop onNavigate={spy} />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowUp'}); expect(spy).toHaveBeenCalledTimes(2); expect(spy).toHaveBeenCalledWith(null); cleanup(); }); }); describe('openOnArrowKeyDown', () => { test('true ArrowDown', () => { render(<App openOnArrowKeyDown={true} />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.getByRole('menu')).toBeInTheDocument(); cleanup(); }); test('true ArrowUp', () => { render(<App openOnArrowKeyDown={true} />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowUp'}); expect(screen.getByRole('menu')).toBeInTheDocument(); cleanup(); }); test('false ArrowDown', () => { render(<App openOnArrowKeyDown={false} />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.queryByRole('menu')).not.toBeInTheDocument(); cleanup(); }); test('false ArrowUp', () => { render(<App openOnArrowKeyDown={false} />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowUp'}); expect(screen.queryByRole('menu')).not.toBeInTheDocument(); cleanup(); }); }); describe('disabledIndices', () => { test('indicies are skipped in focus order', () => { render(<App disabledIndices={[0]} />); fireEvent.keyDown(screen.getByRole('button'), {key: 'ArrowDown'}); expect(screen.getByTestId('item-1')).toHaveFocus(); fireEvent.keyDown(screen.getByRole('menu'), {key: 'ArrowUp'}); expect(screen.getByTestId('item-1')).toHaveFocus(); cleanup(); }); }); describe('focusOnHover', () => { test('true - focuses item on hover and syncs the active index', () => { const spy = jest.fn(); render(<App onNavigate={spy} />); fireEvent.click(screen.getByRole('button')); fireEvent.mouseMove(screen.getByTestId('item-1')); expect(screen.getByTestId('item-1')).toHaveFocus(); fireEvent.mouseLeave(screen.getByTestId('item-1')); expect(screen.getByRole('menu')).toHaveFocus(); expect(spy).toHaveBeenCalledWith(1); cleanup(); }); test('false - does not focus item on hover and does not sync the active index', () => { const spy = jest.fn(); render(<App onNavigate={spy} focusItemOnHover={false} />); fireEvent.click(screen.getByRole('button')); fireEvent.mouseMove(screen.getByTestId('item-1')); expect(screen.getByTestId('item-1')).not.toHaveFocus(); expect(spy).toHaveBeenCalledTimes(0); cleanup(); }); });
the_stack
import express from "express"; import multer from "multer"; import fs from "fs"; import cors from "cors"; import path from "path"; import chalk from "chalk"; import bodyParser from "body-parser"; import os from "os"; import uploadAsset from "../helpers/uploadAsset"; import exportMission from "../imports/missions/export"; import importMission from "../imports/missions/import"; import exportSimulator from "../imports/simulators/export"; import importSimulator from "../imports/simulators/import"; import importAssets from "../imports/asset/import"; import exportLibrary from "../imports/library/export"; import importLibrary from "../imports/library/import"; import exportKeyboard from "../imports/keyboards/export"; import importKeyboard from "../imports/keyboards/import"; import exportTacticalMap from "../imports/tacticalMaps/export"; import importTacticalMap from "../imports/tacticalMaps/import"; import exportSoftwarePanel from "../imports/softwarePanels/export"; import importSoftwarePanel from "../imports/softwarePanels/import"; import exportFlight from "../imports/flights/export"; import importFlight from "../imports/flights/import"; import exportTrigger from "../imports/triggers/export"; import importTrigger from "../imports/triggers/import"; // import exportSurvey from "../imports/surveys/export"; // import importSurvey from "../imports/surveys/import"; import exportCoreLayout from "../imports/coreLayout/export"; import importCoreLayout from "../imports/coreLayout/import"; import errorhandler from "errorhandler"; import App from "../app"; import yazl from "yazl"; import yauzl from "yauzl"; import paths from "../helpers/paths"; import {pascalCase} from "change-case"; import * as classes from "../classes"; import mkdirp from "mkdirp"; let assetDir = path.resolve("./"); if (process.env.NODE_ENV === "production") { assetDir = paths.userData; } export interface MulterFile { key: string; // Available using `S3`. path: string; // Available using `DiskStorage`. mimetype: string; originalname: string; size: number; } const exportsHandlers = { exportMission: exportMission, exportSimulator: exportSimulator, exportKeyboard: exportKeyboard, exportTacticalMap: exportTacticalMap, exportSoftwarePanel: exportSoftwarePanel, exportFlight, exportTrigger, // exportSurvey, exportCoreLayout, }; const importsHandlers = { importSimulator: importSimulator, importMission: importMission, importKeyboard: importKeyboard, importTacticalMap: importTacticalMap, importAssets: importAssets, importSoftwarePanel: importSoftwarePanel, importFlight, importTrigger, // importSurvey, importCoreLayout, }; const tmpDir = os.tmpdir(); const folder = `${tmpDir}${path.sep}`; export default () => { const upload = multer({ dest: folder, }); const server = express(); server.use(errorhandler({log: true})); server.use(bodyParser.json({limit: "20mb"})); // server.use(require("express-status-monitor")({})); server.use("*", cors()); // server.use("/schema", (req, res) => { // res.set("Content-Type", "text/plain"); // res.send(printSchema(schema)); // }); server.post("/upload", upload.any(), async (req, res) => { uploadAsset({}, Object.assign({}, req.body, {files: req.files}), {}); res.end(JSON.stringify("success!")); }); // Dynamic object exports Object.entries(exportsHandlers).forEach(([key, func]) => { server.get(`/${key}/:id`, (req, res) => { func(req.params.id, res); }); }); // Generic imports and exports interface Exportable { exportable: string; } function streamToString(stream, cb) { const chunks = []; stream.on("data", chunk => { chunks.push(chunk.toString()); }); stream.on("end", () => { cb(chunks.join("")); }); } Object.entries(classes).forEach(([classKey, classObj]) => { const exportObj = (classObj as unknown) as Exportable; if (exportObj.exportable) { server.get( `/export${pascalCase(exportObj.exportable)}/:id`, (req, res) => { const id = req.params.id.split(","); const objects = App?.[exportObj.exportable]?.filter(o => id.includes(o.id), ); if (objects.length === 0) { res.end(`No ${classKey}`); return; } if (!objects[0]?.serialize) { res.end(`Cannot export ${classKey}`); return; } const zipfile = new yazl.ZipFile(); function addAsset(fileName) { let key = fileName; if (!key.split(".")[1]) { // No extension - find the most likely candidate const path = key.split("/").slice(0, -1).join("/"); const filename = key.split("/")[key.split("/").length - 1]; const folderPath = assetDir + "/assets" + path; if (!fs.existsSync(folderPath)) return; const files = fs.readdirSync(folderPath); const file = files .filter(f => !fs.statSync(folderPath + "/" + f).isDirectory()) .find(f => f.indexOf(filename) > -1); if (!file) { console.error("Couldn't find file:", key); return; } key = path + "/" + file; } if (key.url) { const fileLoc = `${assetDir}/${key.url}`.replace("//", "/"); if (fs.existsSync(fileLoc)) { zipfile.addFile(fileLoc, `${exportObj.exportable}${key.url}`); } } else { const objectLoc = `${assetDir}/assets/${key}`.replace("//", "/"); if (!fs.existsSync(objectLoc)) return; zipfile.addFile( objectLoc, `${exportObj.exportable}/assets${key}`, { mtime: new Date(), mode: parseInt("0100664", 8), // -rw-rw-r-- }, ); } } let allData = {}; function addData(key: string, data: any) { allData[key] = allData[key] ? allData[key].concat(data) : [data]; } let exportName; objects.forEach(obj => { exportName = obj.serialize({addData, addAsset}) || exportName; }); const buff = Buffer.from(JSON.stringify(allData)); zipfile.addBuffer(buff, `${exportObj.exportable}/data.json`, { mtime: new Date(), mode: parseInt("0100664", 8), // -rw-rw-r-- }); zipfile.end({forceZip64Format: false}, function () { res.set({ "Content-Disposition": `attachment; filename=${exportName}`, "Content-Type": "application/octet-stream", }); zipfile.outputStream.pipe(res); }); }, ); server.post( `/import${pascalCase(exportObj.exportable)}`, upload.any(), async (req: express.Request & {files: MulterFile[]}, res) => { console.log(`Importing ${pascalCase(exportObj.exportable)}`); if (req.files[0]) { const importZip = await new Promise<yauzl.ZipFile>( (resolve, reject) => yauzl.open(req.files[0].path, {lazyEntries: true}, function ( err, importZip, ) { if (err) reject(err); resolve(importZip); }), ); importZip.on("entry", function (entry) { if (entry.fileName.includes("data.json")) { // It's the data file. Read it, parse it, and load the data. importZip.openReadStream(entry, function (error, readStream) { if (error) throw error; streamToString(readStream, str => { const data = JSON.parse(str); Object.values(data).forEach((data: unknown[]) => { // All values in the export are arrays; loop over them data.forEach(obj => { const Class = classes[(obj as {class: string}).class]; if (!Class) { console.error( "Error importing file: could not find class for ", Class, ); } if (!Class.import) { console.error( `Error importing file: class "${Class}" has not implemented an import function.`, ); } Class.import(obj); }); }); importZip.readEntry(); }); }); } else { // It's an asset. Load it into the file system. importZip.openReadStream(entry, function (error, readStream) { if (error) throw error; readStream.on("end", function () { importZip.readEntry(); }); let filename = entry.fileName.replace( `${exportObj.exportable}/`, "", ); const directoryPath = filename .split("/") .splice(0, filename.split("/").length - 1) .join("/"); mkdirp.sync(`${assetDir}/${directoryPath}`); readStream.pipe( fs.createWriteStream(`${assetDir}/${filename}`), ); }); } }); importZip.on("close", () => { fs.unlink(req.files[0].path, err => { if (err) { res.end("Error"); } res.end("Complete"); }); }); importZip.readEntry(); } }, ); } }); server.get("/exportLibrary/:simId", (req, res) => { exportLibrary(req.params.simId, null, res); }); server.get("/exportLibrary/:simId/:entryId", (req, res) => { exportLibrary(req.params.simId, req.params.entryId, res); }); Object.entries(importsHandlers).forEach(([key, func]) => { server.post( `/${key}`, upload.any(), async (req: express.Request & {files: MulterFile[]}, res) => { if (req.files[0]) { func(req.files[0].path, () => { fs.unlink(req.files[0].path, err => { if (err) { res.end("Error"); } res.end("Complete"); }); }); } }, ); }); server.post( "/importLibrary/:simId", upload.any(), async (req: express.Request & {files: MulterFile[]}, res) => { const {simId} = req.params; if (req.files[0]) { importLibrary(req.files[0].path, simId, () => { fs.unlink(req.files[0].path, err => { if (err) { res.end("Error"); } res.end("Complete"); }); }); } }, ); if (process.env.NODE_ENV === "production") { // If we're in production, the last thing we want is for the server to crash // Print all server errors, but don't terminate the process setInterval(function () {}, Math.pow(2, 31) - 1); process.on("uncaughtException", err => { console.error(chalk.red(`Caught exception: ${err}\n`)); console.error(err); }); } else { server.use("/assets/", express.static(path.resolve("./assets"))); } // console.info(server._router.stack.map(r => r.route?.path).filter(Boolean)); return server; };
the_stack
import { ClassType, CustomError, isObject } from '@deepkit/core'; import { tearDown } from '@deepkit/core-rxjs'; import { arrayBufferTo, Entity, propertyDefinition, t } from '@deepkit/type'; import { BehaviorSubject, Observable, Subject, TeardownLogic } from 'rxjs'; import { skip } from 'rxjs/operators'; export type IdType = string | number; export interface IdInterface { id: IdType; } export interface IdVersionInterface extends IdInterface { version: number; } export class ConnectionWriter { write(buffer: Uint8Array) { } } export class StreamBehaviorSubject<T> extends BehaviorSubject<T> { public readonly appendSubject = new Subject<T>(); protected nextChange?: Subject<void>; protected nextOnAppend = false; protected unsubscribed = false; protected teardowns: TeardownLogic[] = []; constructor( item: T, teardown?: TeardownLogic, ) { super(item); if (teardown) { this.teardowns.push(teardown); } } public isUnsubscribed(): boolean { return this.unsubscribed; } get nextStateChange() { if (!this.nextChange) { this.nextChange = new Subject<void>(); } return this.nextChange.toPromise(); } addTearDown(teardown: TeardownLogic) { if (this.unsubscribed) { tearDown(teardown); return; } this.teardowns.push(teardown); } /** * This method differs to BehaviorSubject in the way that this does not throw an error * when the subject is closed/unsubscribed. */ getValue(): T { if (this.hasError) { throw this.thrownError; } else { return (this as any)._value; } } next(value: T): void { super.next(value); if (this.nextChange) { this.nextChange.complete(); delete this.nextChange; } } activateNextOnAppend() { this.nextOnAppend = true; } toUTF8() { const subject = new StreamBehaviorSubject(this.value instanceof Uint8Array ? arrayBufferTo(this.value, 'utf8') : ''); const sub1 = this.pipe(skip(1)).subscribe(v => { subject.next(v instanceof Uint8Array ? arrayBufferTo(v, 'utf8') : ''); }); const sub2 = this.appendSubject.subscribe(v => { subject.append(v instanceof Uint8Array ? arrayBufferTo(v, 'utf8') : ''); }); subject.nextOnAppend = this.nextOnAppend; // const that = this; // Object.defineProperty(subject, 'nextStateChange', { // get() { // console.log('utf8 nextStateChange'); // return that.nextStateChange; // } // }); subject.addTearDown(() => { sub1.unsubscribe(); sub2.unsubscribe(); this.unsubscribe(); }); return subject; } append(value: T): void { this.appendSubject.next(value); if (this.nextOnAppend) { if (value instanceof Uint8Array) { if (this.value instanceof Uint8Array) { this.next(Buffer.concat([this.value as any, value as any]) as any); } else { this.next(value as any); } } else { this.next((this.getValue() as any + value) as any as T); } } else { if ('string' === typeof value) { if (!(this as any)._value) ((this as any)._value as any) = ''; ((this as any)._value as any) = ((this as any)._value as any) + value; } } } unsubscribe(): void { if (this.unsubscribed) return; this.unsubscribed = true; for (const teardown of this.teardowns) { tearDown(teardown); } super.unsubscribe(); } } const IsEntitySubject = Symbol.for('deepkit/entitySubject'); export function isEntitySubject(v: any): v is EntitySubject<any> { return !!v && isObject(v) && v.hasOwnProperty(IsEntitySubject); } export class EntitySubject<T extends IdInterface> extends StreamBehaviorSubject<T> { /** * Patches are in class format. */ public readonly patches = new Subject<EntityPatch>(); public readonly delete = new Subject<boolean>(); [IsEntitySubject] = true; public deleted: boolean = false; get id(): string | number { return this.value.id; } get onDeletion(): Observable<void> { return new Observable((observer) => { if (this.deleted) { observer.next(); return; } const sub = this.delete.subscribe(() => { observer.next(); sub.unsubscribe(); }); return { unsubscribe(): void { sub.unsubscribe(); } }; }); } next(value: T | undefined): void { if (value === undefined) { this.deleted = true; this.delete.next(true); super.next(this.value); return; } super.next(value); } } export class ControllerDefinition<T> { constructor( public path: string, public entities: ClassType[] = [] ) { } } export function ControllerSymbol<T>(path: string, entities: ClassType[] = []): ControllerDefinition<T> { return new ControllerDefinition<T>(path, entities); } @Entity('@error:json') export class JSONError { constructor(@t.any.name('json') public readonly json: any) { } } export class ValidationErrorItem { constructor( @t.name('path') public readonly path: string, @t.name('code') public readonly code: string, @t.name('message') public readonly message: string, ) { } toString() { return `${this.path}(${this.code}): ${this.message}`; } } @Entity('@error:validation') export class ValidationError extends CustomError { constructor( @t.array(ValidationErrorItem).name('errors') public readonly errors: ValidationErrorItem[] ) { super(errors.map(v => `${v.path}(${v.code}): ${v.message}`).join(',')); } static from(errors: { path: string, message: string, code?: string }[]) { return new ValidationError(errors.map(v => new ValidationErrorItem(v.path, v.message, v.code || ''))); } } @Entity('@error:parameter') export class ValidationParameterError { constructor( @t.name('controller') public readonly controller: string, @t.name('action') public readonly action: string, @t.name('arg') public readonly arg: number, @t.array(ValidationErrorItem).name('errors') public readonly errors: ValidationErrorItem[] ) { } get message(): string { return this.errors.map(v => `${v.path}: ${v.message} (${v.code})`).join(','); } } export enum RpcTypes { Ack, Error, //A batched chunk. Used when a single message exceeds a certain size. It's split up in multiple packages, allowing to track progress, //cancel, and safe memory. Allows to send shorter messages between to not block the connection. Both ways. Chunk, ChunkAck, Ping, Pong, //client -> server Authenticate, ActionType, Action, //T is the parameter type [t.string, t.number, ...] (typed arrays not supported yet) PeerRegister, PeerDeregister, //server -> client ClientId, ClientIdResponse, AuthenticateResponse, ResponseActionType, ResponseActionReturnType, ResponseActionSimple, //direct response that can be simple deserialized. ResponseActionResult, //composite message, first optional ResponseActionType, second ResponseAction* ActionObservableSubscribe, ActionObservableUnsubscribe, ActionObservableDisconnect, //removed a stored Observable instance so it can not longer create new observers and unsubscribe all subscriptions ActionObservableSubjectUnsubscribe, ResponseActionObservable, ResponseActionBehaviorSubject, ResponseActionObservableNext, ResponseActionObservableComplete, ResponseActionObservableError, ActionCollectionUnsubscribe, //when client unsubscribed collection ActionCollectionModel, //when client updated model ResponseActionCollection, ResponseActionCollectionModel, ResponseActionCollectionSort, ResponseActionCollectionState, ResponseActionCollectionChange, ResponseActionCollectionSet, ResponseActionCollectionAdd, ResponseActionCollectionRemove, ResponseActionCollectionUpdate, ResponseEntity, //single entity sent Entity, //change feed as composite, containing all Entity* EntityPatch, EntityRemove, } export const rpcClientId = t.schema({ id: t.type(Uint8Array) }); export const rpcChunk = t.schema({ id: t.number, //chunk id total: t.number, //size in bytes v: t.type(Uint8Array), }); export const rpcActionObservableSubscribeId = t.schema({ id: t.number, }); export const rpcError = t.schema({ classType: t.string, message: t.string, stack: t.string, properties: t.map(t.any).optional, }); export const rpcResponseActionObservableSubscriptionError = rpcError.extend({ id: t.number }); export enum ActionObservableTypes { observable, subject, behaviorSubject, } export const rpcSort = t.schema({ field: t.string, direction: t.union('asc', 'desc'), }); export const rpcResponseActionObservable = t.schema({ type: t.enum(ActionObservableTypes) }); export const rpcAuthenticate = t.schema({ token: t.any, }); export const rpcResponseAuthenticate = t.schema({ username: t.string, }); export const rpcAction = t.schema({ controller: t.string, method: t.string, }); export const rpcActionType = t.schema({ controller: t.string, method: t.string, disableTypeReuse: t.boolean.optional, }); export const rpcResponseActionType = t.schema({ parameters: t.array(propertyDefinition), result: t.type(propertyDefinition), next: t.type(propertyDefinition).optional, }); export const rpcPeerRegister = t.schema({ id: t.string, }); export const rpcPeerDeregister = t.schema({ id: t.string, }); export const rpcResponseActionCollectionRemove = t.schema({ ids: t.array(t.union(t.string, t.number)), }); export const rpcResponseActionCollectionSort = t.schema({ ids: t.array(t.union(t.string, t.number)), }); export const rpcEntityRemove = t.schema({ entityName: t.string, ids: t.array(t.union(t.string, t.number)), }); export interface EntityPatch { $set?: { [path: string]: any }, $unset?: { [path: string]: number } $inc?: { [path: string]: number } } export const rpcEntityPatch = t.schema({ entityName: t.string, id: t.union(t.string, t.number), version: t.number, patch: t.type({ $set: t.map(t.any).optional, $unset: t.map(t.number).optional, $inc: t.map(t.number).optional, }) }); export class AuthenticationError extends Error { constructor(message: string = 'Authentication failed') { super(message); } }
the_stack
import {CommonModule} from '@angular/common'; import {DebugElement} from '@angular/core'; import {async, ComponentFixture, fakeAsync, TestBed} from '@angular/core/testing'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {MatButtonModule, MatDialogModule, MatDialogRef, MatIconModule, MatProgressSpinnerModule, MatSelectModule} from '@angular/material'; import {MAT_DIALOG_DATA} from '@angular/material'; import {By} from '@angular/platform-browser'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {Subject} from 'rxjs/Subject'; import {FormSpinnerModule} from '../../common/components/form-spinner/form-spinner.module'; // tslint:disable-next-line:max-line-length import {expectElementNotToExist, expectElementToExist, expectInputControlToBeAttachedToForm, getElement, getElementText} from '../../common/test_helpers/element_helper_functions'; import {mockLanes, mockLanesResponse} from '../../common/test_helpers/mock_lane_data'; import {mockProjectSummary} from '../../common/test_helpers/mock_project_data'; import {mockRepositoryList} from '../../common/test_helpers/mock_repository_data'; import {Lane} from '../../models/lane'; import {ProjectSummary} from '../../models/project_summary'; import {Repository} from '../../models/repository'; import {DataService} from '../../services/data.service'; import {AddProjectDialogComponent} from './add-project-dialog.component'; describe('AddProjectDialogComponent', () => { let component: AddProjectDialogComponent; let fixture: ComponentFixture<AddProjectDialogComponent>; let fixtureEl: DebugElement; let reposSubject: Subject<Repository[]>; let projectSubject: Subject<ProjectSummary>; let lanesSubject: Subject<Lane[]>; let dataService: jasmine.SpyObj<Partial<DataService>>; let projectNameEl: HTMLInputElement; let repoSelectEl: HTMLElement; let laneSelectEl: HTMLElement; let triggerSelectEl: HTMLElement; let dialogRef: jasmine.SpyObj<Partial<MatDialogRef<AddProjectDialogComponent>>>; beforeEach(async(() => { reposSubject = new Subject<Repository[]>(); projectSubject = new Subject<ProjectSummary>(); lanesSubject = new Subject<Lane[]>(); dataService = { addProject: jasmine.createSpy().and.returnValue(projectSubject.asObservable()), getRepoLanes: jasmine.createSpy().and.returnValue(lanesSubject.asObservable()) }; dialogRef = {close: jasmine.createSpy()}; TestBed .configureTestingModule({ declarations: [AddProjectDialogComponent], providers: [ { provide: MAT_DIALOG_DATA, useValue: {repositories: reposSubject.asObservable()} }, {provide: DataService, useValue: dataService}, {provide: MatDialogRef, useValue: dialogRef} ], imports: [ MatDialogModule, MatButtonModule, MatSelectModule, MatIconModule, CommonModule, ReactiveFormsModule, FormSpinnerModule, MatProgressSpinnerModule, BrowserAnimationsModule ] }) .compileComponents(); fixture = TestBed.createComponent(AddProjectDialogComponent); fixtureEl = fixture.debugElement; component = fixture.componentInstance; fixture.detectChanges(); projectNameEl = getElement(fixtureEl, 'input[placeholder="Project Name"]') .nativeElement; repoSelectEl = getElement(fixtureEl, '.fci-repo-select').nativeElement; laneSelectEl = getElement(fixtureEl, '.fci-lane-select').nativeElement; triggerSelectEl = getElement(fixtureEl, '.fci-trigger-select').nativeElement; })); it('Should close dialog when close button is clicked', () => { getElement(fixtureEl, '.mat-dialog-actions > .mat-button') .nativeElement.click(); expect(dialogRef.close).toHaveBeenCalled(); }); it('Should close dialog when X button is clicked', () => { getElement(fixtureEl, '.fci-dialog-icon-close-button') .nativeElement.click(); expect(dialogRef.close).toHaveBeenCalled(); }); describe('initialization', () => { it('should enable controls once repo data is loaded', async(() => { expect(component.form.get('repo').enabled).toBe(false); expect(component.form.get('name').enabled).toBe(false); expect(component.form.get('trigger').enabled).toBe(false); // Load Repos reposSubject.next(mockRepositoryList); expect(component.form.get('repo').enabled).toBe(true); expect(component.form.get('name').enabled).toBe(true); expect(component.form.get('trigger').enabled).toBe(true); })); it('should enable lane once lane data is loaded', async(() => { expect(component.form.get('lane').enabled).toBe(false); // Load Repos and Lanes reposSubject.next(mockRepositoryList); lanesSubject.next(mockLanes); expect(component.form.get('repo').enabled).toBe(true); expect(component.form.get('name').enabled).toBe(true); expect(component.form.get('trigger').enabled).toBe(true); })); }); describe('repo, lane, project name form controls', () => { beforeEach(() => { // Load Repos reposSubject.next(mockRepositoryList); fixture.detectChanges(); }); it('should bind the project name input', async(() => { component.form.patchValue({'name': 'ProjectX'}); fixture.detectChanges(); fixture.whenStable().then(() => { expectInputControlToBeAttachedToForm( fixture, 'name', component.form); }); })); it('should set repo option', () => { component.form.patchValue({'repo': 'fastlane/fastlane'}); fixture.detectChanges(); expect(repoSelectEl.textContent).toBe('fastlane/fastlane'); component.form.patchValue({'repo': 'fastlane/ci'}); fixture.detectChanges(); expect(repoSelectEl.textContent).toBe('fastlane/ci'); }); it('should set lane option', async(() => { // Load Lanes lanesSubject.next(mockLanes); fixture.detectChanges(); fixture.whenStable().then(() => { component.form.patchValue({'lane': 'ios test'}); fixture.detectChanges(); expect(laneSelectEl.textContent).toBe('ios test'); component.form.patchValue({'lane': 'android beta'}); fixture.detectChanges(); expect(laneSelectEl.textContent).toBe('android beta'); }); })); it('should reload lanes if repo changes', () => { // Load Lanes lanesSubject.next(mockLanes); expect(component.isLoadingLanes).toBe(false); expect(component.lanes.length).toBe(2); // Select the third repo component.form.patchValue({'repo': component.repositories[2]}); // Assert that the new lanes are loaded expect(component.isLoadingLanes).toBe(true); lanesSubject.next([mockLanes[0]]); expect(component.isLoadingLanes).toBe(false); expect(component.lanes.length).toBe(1); }); it('should show spinner when lanes are loading', () => { expect(component.isLoadingLanes).toBe(true); expectElementToExist(fixtureEl, '.fci-lane-form .mat-spinner'); lanesSubject.next(mockLanes); fixture.detectChanges(); expect(component.isLoadingLanes).toBe(false); expectElementNotToExist(fixtureEl, '.fci-lane-form .mat-spinner'); }); }); describe('triggers', () => { beforeEach(() => { // Load Repos reposSubject.next(mockRepositoryList); fixture.detectChanges(); }); it('should show correct nightly trigger option name', () => { component.form.patchValue({'trigger': 'nightly'}); fixture.detectChanges(); expect(triggerSelectEl.textContent).toBe('nightly'); }); it('should show correct commit option name', () => { component.form.patchValue({'trigger': 'commit'}); fixture.detectChanges(); expect(triggerSelectEl.textContent).toBe('for every commit'); }); it('should show correct PR option name', () => { component.form.patchValue({'trigger': 'pull_request'}); fixture.detectChanges(); expect(triggerSelectEl.textContent).toBe('for every pull request'); }); it('should show time selection when trigger is nightly', () => { component.form.patchValue({'trigger': 'nightly'}); fixture.detectChanges(); expectElementToExist(fixtureEl, '.fci-hour-select'); expectElementToExist(fixtureEl, '.fci-am-pm-select'); }); it('should not show time selection when trigger is not nightly', () => { component.form.patchValue({'trigger': 'commit'}); fixture.detectChanges(); expectElementNotToExist(fixtureEl, '.fci-hour-select'); expectElementNotToExist(fixtureEl, '.fci-am-pm-select'); }); it('should set nightly time correctly', async(() => { component.form.patchValue({'trigger': 'nightly'}); fixture.detectChanges(); const hourEl = getElement(fixtureEl, '.fci-hour-select'); const amPmEl = getElement(fixtureEl, '.fci-am-pm-select'); // I think this is needed to load the hour/amPm select in ngIf block fixture.whenStable().then(() => { fixture.detectChanges(); expect(getElementText(hourEl)).toBe('12'); expect(getElementText(amPmEl)).toBe('AM'); component.form.patchValue({'hour': 2, 'amPm': 'PM'}); fixture.detectChanges(); expect(getElementText(hourEl)).toBe('2'); expect(getElementText(amPmEl)).toBe('PM'); }); })); }); describe('#addProject', () => { beforeEach(() => { // Load Repos reposSubject.next(mockRepositoryList); // Load Lanes lanesSubject.next(mockLanes); fixture.detectChanges(); // Set the name control so the form is valid component.form.patchValue({'name': 'fake project'}); }); it('should not add project if form is invalid', () => { // invalidate form component.form.patchValue({'name': ''}); expect(component.form.valid).toBe(false); component.addProject(); expect(dataService.addProject).not.toHaveBeenCalled(); }); it('should add project with correct form data', () => { component.form.setValue({ 'name': 'fake name', 'lane': 'fake lane', 'repo': 'fake repo', 'trigger': 'nightly', 'hour': 2, 'amPm': 'PM' }); expect(component.form.valid).toBe(true); component.addProject(); expect(dataService.addProject).toHaveBeenCalledWith({ 'project_name': 'fake name', 'lane': 'fake lane', 'repo_org': '', 'repo_name': 'fake repo', 'trigger_type': 'nightly', 'branch': 'master', 'hour': 14, }); }); it('should emit add project event when project is added', () => { let projectSummary: ProjectSummary; component.addProject(); component.projectAdded.subscribe((summary: ProjectSummary) => { projectSummary = summary; }); projectSubject.next(mockProjectSummary); expect(projectSummary).toBe(mockProjectSummary); }); it('should add the project hour in military time when nightly trigger', () => { component.form.patchValue({'trigger': 'nightly'}); // 1PM or 13:00 component.form.patchValue({'hour': 1, 'amPm': 'PM'}); component.addProject(); expect(dataService.addProject.calls.mostRecent().args[0].hour) .toBe(13); // Midnight or 0:00 component.form.patchValue({'hour': 12, 'amPm': 'AM'}); component.addProject(); expect(dataService.addProject.calls.mostRecent().args[0].hour).toBe(0); }); it('should show spinner while adding project', () => { expectElementNotToExist(fixtureEl, '.mat-spinner'); component.addProject(); fixture.detectChanges(); expectElementToExist(fixtureEl, '.mat-spinner'); projectSubject.next(mockProjectSummary); fixture.detectChanges(); expectElementNotToExist(fixtureEl, '.mat-spinner'); }); it('should close dialog on success', async(() => { // TODO: figure out how to submit the test from clicking the UI // button component.addProject(); projectSubject.next(mockProjectSummary); expect(dialogRef.close).toHaveBeenCalled(); })); }); });
the_stack
import { CodyResponse, CodyResponseType, followPlaylist, getPlaylists, getPlaylistTracks, getRecommendationsForTracks, getSpotifyAlbumTracks, getSpotifyDevices, getSpotifyLikedSongs, getSpotifyPlayerContext, getSpotifyPlaylist, PaginationItem, PlayerContext, PlayerDevice, PlayerName, PlayerType, PlaylistItem, PlaylistTrackInfo, removeTracksFromPlaylist, Track, } from "cody-music"; import { commands, window } from "vscode"; import { RECOMMENDATION_LIMIT, RECOMMENDATION_PLAYLIST_ID, SOFTWARE_TOP_40_PLAYLIST_ID } from "../app/utils/view_constants"; import { OK_LABEL, SPOTIFY_LIKED_SONGS_PLAYLIST_ID, SPOTIFY_LIKED_SONGS_PLAYLIST_NAME, YES_LABEL } from "../app/utils/view_constants"; import { isResponseOk, softwareGet } from "../HttpClient"; import MusicMetrics from "../model/MusicMetrics"; import MusicScatterData from "../model/MusicScatterData"; import { MusicCommandManager } from "../music/MusicCommandManager"; import { MusicCommandUtil } from "../music/MusicCommandUtil"; import { MusicControlManager } from "../music/MusicControlManager"; import { MusicStateManager } from "../music/MusicStateManager"; import { getCodyErrorMessage, isMac } from "../Util"; import { getItem } from "./FileManager"; import { connectSpotify, getSpotifyIntegration, populateSpotifyUser, updateCodyConfig, updateSpotifyClientInfo } from "./SpotifyManager"; let currentDevices: PlayerDevice[] = []; let spotifyLikedTracks: PlaylistItem[] = undefined; let spotifyPlaylists: PlaylistItem[] = undefined; let softwareTop40Playlist: PlaylistItem = undefined; let recommendedTracks: PlaylistItem[] = undefined; let playlistTracks: any = {}; let musicScatterData: MusicScatterData = undefined; let userMusicMetrics: MusicMetrics[] = undefined; let averageMusicMetrics: MusicMetrics = undefined; let selectedPlaylistId = undefined; let selectedTrackItem: PlaylistItem = undefined; let cachedRunningTrack: Track = undefined; let spotifyContext: PlayerContext = undefined; let selectedPlayerName = PlayerName.SpotifyWeb; // playlists, recommendations, metrics let selectedTabView = "playlists"; let recommendationMetadata: any = undefined; let recommendationInfo: any = undefined; let sortAlphabetically: boolean = false; //////////////////////////////////////////////////////////////// // CLEAR DATA EXPORTS //////////////////////////////////////////////////////////////// export function clearAllData() { clearSpotifyLikedTracksCache(); clearSpotifyPlaylistsCache(); clearSpotifyDevicesCache(); selectedPlaylistId = undefined; selectedTrackItem = undefined; } export function clearSpotifyLikedTracksCache() { spotifyLikedTracks = undefined; } export function clearSpotifyPlaylistsCache() { spotifyPlaylists = undefined; } export function clearSpotifyDevicesCache() { currentDevices = undefined; } export function clearSpotifyPlayerContext() { spotifyContext = null; } //////////////////////////////////////////////////////////////// // UPDATE EXPORTS //////////////////////////////////////////////////////////////// export function updateSpotifyPlaylists(playlists) { spotifyPlaylists = playlists; } export function updateSpotifyLikedTracks(songs) { spotifyLikedTracks = songs; } export function removeTrackFromLikedPlaylist(trackId) { spotifyLikedTracks = spotifyLikedTracks.filter((n) => n.id !== trackId); } export function addTrackToLikedPlaylist(playlistItem: PlaylistItem) { playlistItem["liked"] = true; playlistItem["playlist_id"] = SPOTIFY_LIKED_SONGS_PLAYLIST_ID; spotifyLikedTracks.unshift(playlistItem); } export function updateSpotifyPlaylistTracks(playlist_id, songs) { playlistTracks[playlist_id] = songs; } export function updateSelectedTrackItem(item) { selectedTrackItem = item; selectedPlaylistId = item["playlist_id"]; } export function updateSelectedPlaylistId(playlist_id) { selectedPlaylistId = playlist_id; } export function updateSelectedPlayer(player: PlayerName) { selectedPlayerName = player; } export function updateSelectedTabView(tabView: string) { selectedTabView = tabView; } export function updateSort(alphabetically: boolean) { sortAlphabetically = alphabetically; sortPlaylists(spotifyPlaylists, alphabetically); commands.executeCommand("musictime.refreshMusicTimeView"); } export function updateCachedRunningTrack(track: Track) { cachedRunningTrack = track; // track has been updated, refresh the webview commands.executeCommand("musictime.refreshMusicTimeView"); } export function updateLikedStatusInPlaylist(playlist_id, track_id, liked_state) { let item: PlaylistItem = playlistTracks[playlist_id]?.length ? playlistTracks[playlist_id].find((n) => n.id === track_id) : null; if (item) { item["liked"] = liked_state; } // it might be in the recommendations list item = recommendationInfo.tracks?.find((n) => n.id === track_id); if (item) { item["liked"] = liked_state; } } //////////////////////////////////////////////////////////////// // CACHE GETTERS //////////////////////////////////////////////////////////////// export async function getCachedSpotifyPlaylists() { if (!spotifyPlaylists) { spotifyPlaylists = await getSpotifyPlaylists(); } return spotifyPlaylists; } export function getCachedPlaylistTracks() { return playlistTracks; } export function getCachedLikedSongsTracks() { return spotifyLikedTracks; } export async function getCachedSoftwareTop40Playlist() { if (!softwareTop40Playlist) { softwareTop40Playlist = await getSoftwareTop40Playlist(); } return softwareTop40Playlist; } export function getCachedRecommendationInfo() { return recommendationInfo; } export async function getCachedUserMetricsData() { if (!userMusicMetrics) { await getUserMusicMetrics(); } return { userMusicMetrics, averageMusicMetrics, musicScatterData }; } export function getCachedRecommendationMetadata() { return recommendationMetadata; } export async function getPlayerContext() { return await getSpotifyPlayerContext(); } export function getCachedRunningTrack() { return cachedRunningTrack; } export function getSelectedPlaylistId() { return selectedPlaylistId; } export function getSelectedPlayerName() { return selectedPlayerName; } export function getSelectedTrackItem() { return selectedTrackItem; } export function getSelectedTabView() { return selectedTabView; } // only playlists (not liked or recommendations) export function getPlaylistById(playlist_id) { if (SOFTWARE_TOP_40_PLAYLIST_ID === playlist_id) { return softwareTop40Playlist; } return spotifyPlaylists?.find((n) => n.id === playlist_id); } export function isLikedSongPlaylistSelected() { return !!(selectedPlaylistId === SPOTIFY_LIKED_SONGS_PLAYLIST_ID); } export function getLikedURIsFromTrackId(trackId) { return getTracksFromTrackId(trackId, spotifyLikedTracks); } export function getRecommendationURIsFromTrackId(trackId) { return getTracksFromTrackId(trackId, recommendationInfo?.tracks); } function createUriFromTrackId(track_id: string) { if (track_id && !track_id.includes("spotify:track:")) { track_id = `spotify:track:${track_id}`; } return track_id; } function getTracksFromTrackId(trackId, existingTracks) { let uris = []; let foundTrack = false; if (existingTracks?.length) { for (const track of existingTracks) { if (!foundTrack && track.id === trackId) { foundTrack = true; } if (foundTrack) { uris.push(createUriFromTrackId(track.id)); } } } if (existingTracks?.length && uris.length < 10) { const limit = 10; // add the ones to the beginning until we've reached 10 or the found track let idx = 0; for (const track of existingTracks) { if (idx >= 10 || (!foundTrack && track.id === trackId)) { break; } uris.push(createUriFromTrackId(track.id)); idx++; } } return uris; } //////////////////////////////////////////////////////////////// // PLAYLIST AND TRACK EXPORTS //////////////////////////////////////////////////////////////// // PLAYLISTS export async function getSpotifyPlaylists(clear = false): Promise<PlaylistItem[]> { if (requiresSpotifyAccess()) { return []; } if (!clear && spotifyPlaylists) { return spotifyPlaylists; } spotifyPlaylists = await getPlaylists(PlayerName.SpotifyWeb, { all: true }); spotifyPlaylists = spotifyPlaylists?.map((n, index) => { return { ...n, index }; }); return spotifyPlaylists; } // LIKED SONGS export function getSpotifyLikedPlaylist() { const item: PlaylistItem = new PlaylistItem(); item.type = "playlist"; item.id = SPOTIFY_LIKED_SONGS_PLAYLIST_ID; item.tracks = new PlaylistTrackInfo(); // set set a number so it shows up item.tracks.total = 1; item.playerType = PlayerType.WebSpotify; item.tag = "spotify-liked-songs"; item.itemType = "playlist"; item.name = SPOTIFY_LIKED_SONGS_PLAYLIST_NAME; return item; } // SOFTWARE TOP 40 export async function getSoftwareTop40Playlist() { softwareTop40Playlist = await getSpotifyPlaylist(SOFTWARE_TOP_40_PLAYLIST_ID); if (softwareTop40Playlist && softwareTop40Playlist.tracks && softwareTop40Playlist.tracks["items"]) { softwareTop40Playlist.tracks["items"] = softwareTop40Playlist.tracks["items"].map((n) => { const albumName = getAlbumName(n.track); const description = getArtistAlbumDescription(n.track); n.track = { ...n.track, albumName, description, playlist_id: SOFTWARE_TOP_40_PLAYLIST_ID }; return { ...n }; }); } return softwareTop40Playlist; } // LIKED PLAYLIST TRACKS export async function fetchTracksForLikedSongs() { selectedPlaylistId = SPOTIFY_LIKED_SONGS_PLAYLIST_ID; if (!spotifyLikedTracks) { await populateLikedSongs(); } // refresh the webview commands.executeCommand("musictime.refreshMusicTimeView"); } // TRACKS FOR A SPECIFIED PLAYLIST export async function fetchTracksForPlaylist(playlist_id) { updateSelectedPlaylistId(playlist_id); if (!playlistTracks[playlist_id]) { const results: CodyResponse = await getPlaylistTracks(PlayerName.SpotifyWeb, playlist_id); let tracks: PlaylistItem[] = await getPlaylistItemTracksFromCodyResponse(results); // add the playlist id to the tracks if (tracks?.length) { for await (const t of tracks) { const albumName = getAlbumName(t); const description = getArtistAlbumDescription(t); t["playlist_id"] = playlist_id; t["albumName"] = albumName; t["description"] = description; t["liked"] = await isLikedSong(t); } } playlistTracks[playlist_id] = tracks; } // refresh the webview commands.executeCommand("musictime.refreshMusicTimeView"); } //////////////////////////////////////////////////////////////// // METRICS EXPORTS //////////////////////////////////////////////////////////////// export async function getUserMusicMetrics() { const resp = await softwareGet("/music/metrics", getItem("jwt")); if (isResponseOk(resp) && resp.data) { userMusicMetrics = resp.data.user_music_metrics; if (userMusicMetrics) { averageMusicMetrics = new MusicMetrics(); musicScatterData = new MusicScatterData(); userMusicMetrics = userMusicMetrics.map((n, index) => { n["keystrokes"] = n.keystrokes ? Math.ceil(n.keystrokes) : 0; n["keystrokes_formatted"] = new Intl.NumberFormat().format(n.keystrokes); n["id"] = n.song_id; n["trackId"] = n.song_id; averageMusicMetrics.increment(n); musicScatterData.addMetric(n); return n; }); averageMusicMetrics.setAverages(userMusicMetrics.length); userMusicMetrics = userMusicMetrics.filter((n) => n.song_name); } } } export async function populateLikedSongs() { const tracks: Track[] = (await getSpotifyLikedSongs()) || []; // add the playlist id to the tracks if (tracks?.length) { spotifyLikedTracks = tracks.map((t, idx) => { const playlistItem: PlaylistItem = createPlaylistItemFromTrack(t, idx); playlistItem["playlist_id"] = SPOTIFY_LIKED_SONGS_PLAYLIST_ID; playlistItem["liked"] = true; return playlistItem; }); } } //////////////////////////////////////////////////////////////// // RECOMMENDATION TRACKS EXPORTS //////////////////////////////////////////////////////////////// export function getCurrentRecommendations() { if (recommendationMetadata) { getRecommendations( recommendationMetadata.length, recommendationMetadata.seedLimit, recommendationMetadata.seed_genres, recommendationMetadata.features, 0 ); } else { getFamiliarRecs(); } } export function getFamiliarRecs() { return getRecommendations("Familiar", 5); } export function getHappyRecs() { return getRecommendations("Happy", 5, [], { min_valence: 0.7, target_valence: 1 }); } export function getEnergeticRecs() { return getRecommendations("Energetic", 5, [], { min_energy: 0.7, target_energy: 1 }); } export function getDanceableRecs() { return getRecommendations("Danceable", 5, [], { min_danceability: 0.5, target_danceability: 1 }); } export function getInstrumentalRecs() { return getRecommendations("Instrumental", 5, [], { min_instrumentalness: 0.6, target_instrumentalness: 1 }); } export function getQuietMusicRecs() { return getRecommendations("Quiet music", 5, [], { max_loudness: -10, target_loudness: -50 }); } export function getMixedAudioFeatureRecs(features) { if (!features) { // fetch familiar getFamiliarRecs(); return; } return getRecommendations("Audio mix", 5, [], features); } export function getTrackRecommendations(playlistItem: PlaylistItem) { return getRecommendations(playlistItem.name, 4, [], {}, 0, [playlistItem]); } export async function getAlbumForTrack(playlistItem: PlaylistItem) { let albumId = playlistItem["albumId"]; let albumName = playlistItem["album"] ? playlistItem["album"]["name"] : ""; if (!albumId && playlistItem["album"]) { albumId = playlistItem["album"]["id"]; } if (albumId) { const albumTracks: Track[] = await getSpotifyAlbumTracks(albumId); let items: PlaylistItem[] = []; if (albumTracks?.length) { let idx = 1; for await (const t of albumTracks) { const playlistItem: PlaylistItem = createPlaylistItemFromTrack(t, idx); if (!t["albumName"]) { t["albumName"] = albumName; } playlistItem["liked"] = await isLikedSong(t); idx++; items.push(playlistItem); } } populateRecommendationTracks(playlistItem["albumName"], items); } } export function refreshRecommendations() { if (!recommendationInfo) { return getFamiliarRecs(); } else { let offset = (recommendationMetadata.offset += 5); if (offset.length - 5 < offset) { // start back at the beginning offset = 0; } getRecommendations( recommendationMetadata.label, recommendationMetadata.seedLimit, recommendationMetadata.seed_genres, recommendationMetadata.features, offset ); } } export async function getRecommendations( label: string, seedLimit: number = 5, seed_genres: string[] = [], features: any = {}, offset: number = 0, seedTracks = [] ) { // set the selectedTabView to "recommendations" selectedTabView = "recommendations"; // fetching recommendations based on a set of genre requires 0 seed track IDs seedLimit = seed_genres.length ? 0 : Math.max(seedLimit, 5); recommendationMetadata = { label, seedLimit, seed_genres, features, offset, }; recommendedTracks = await getTrackIdsForRecommendations(seedLimit, seedTracks, offset).then(async (trackIds) => { const tracks: Track[] = await getRecommendationsForTracks( trackIds, RECOMMENDATION_LIMIT, "" /*market*/, 20, 100, seed_genres, [] /*artists*/, features ); let items: PlaylistItem[] = []; if (tracks?.length) { let idx = 1; for await (const t of tracks) { const playlistItem: PlaylistItem = createPlaylistItemFromTrack(t, idx); playlistItem["playlist_id"] = RECOMMENDATION_PLAYLIST_ID; playlistItem["liked"] = await isLikedSong(t); items.push(playlistItem); idx++; } } return items; }); populateRecommendationTracks(label, recommendedTracks); } export function populateRecommendationTracks(label: string, tracks: PlaylistItem[]) { if (tracks?.length) { tracks = tracks.map((t) => { t["playlist_id"] = RECOMMENDATION_PLAYLIST_ID; const albumName = getAlbumName(t); const description = getArtistAlbumDescription(t); return { ...t, albumName, description }; }); } recommendationInfo = { label, tracks, }; // refresh the webview commands.executeCommand("musictime.refreshMusicTimeView", "recommendations"); } export function removeTracksFromRecommendations(trackId) { let foundIdx = -1; for (let i = 0; i < recommendationInfo.tracks.length; i++) { if (recommendationInfo.tracks[i].id === trackId) { foundIdx = i; break; } } if (foundIdx > -1) { // splice it out recommendationInfo.tracks.splice(foundIdx, 1); } if (recommendationInfo.tracks.length < 2) { // refresh commands.executeCommand("musictime.refreshMusicTimeView"); } } //////////////////////////////////////////////////////////////// // DEVICE EXPORTS //////////////////////////////////////////////////////////////// // POPULATE export async function populateSpotifyDevices(tryAgain = false) { const devices = await MusicCommandUtil.getInstance().runSpotifyCommand(getSpotifyDevices); if (devices.status && devices.status === 429 && tryAgain) { // try one more time in lazily since its not a device launch request. // the device launch requests retries a few times every couple seconds. setTimeout(() => { // use true to specify its a device launch so this doens't try continuously populateSpotifyDevices(false); }, 5000); return; } const fetchedDeviceIds = []; if (devices.length) { devices.forEach((el: PlayerDevice) => { fetchedDeviceIds.push(el.id); }); } let diffDevices = []; if (currentDevices.length) { // get any differences from the fetched devices if any diffDevices = currentDevices.filter((n: PlayerDevice) => !fetchedDeviceIds.includes(n.id)); } else if (fetchedDeviceIds.length) { // no current devices, set diff to whatever we fetched diffDevices = [...devices]; } if (diffDevices.length || currentDevices.length !== diffDevices.length) { // new devices available or setting to empty currentDevices = devices; setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 3000); } } export function getCurrentDevices() { return currentDevices; } export function requiresSpotifyReAuthentication() { const requiresSpotifyReAuth = getItem("requiresSpotifyReAuth"); return requiresSpotifyReAuth ? true : false; } export async function showReconnectPrompt(email) { const reconnectButtonLabel = "Reconnect"; const msg = `To continue using Music Time, please reconnect your Spotify account (${email}).`; const selection = await window.showInformationMessage(msg, ...[reconnectButtonLabel]); if (selection === reconnectButtonLabel) { // now launch re-auth await connectSpotify(); } } /** * returns { webPlayer, desktop, activeDevice, activeComputerDevice, activeWebPlayerDevice } * Either of these values can be null */ export function getDeviceSet() { const webPlayer = currentDevices?.find((d: PlayerDevice) => d.name.toLowerCase().includes("web player")); const desktop = currentDevices?.find((d: PlayerDevice) => d.type.toLowerCase() === "computer" && !d.name.toLowerCase().includes("web player")); const activeDevice = currentDevices?.find((d: PlayerDevice) => d.is_active); const activeComputerDevice = currentDevices?.find((d: PlayerDevice) => d.is_active && d.type.toLowerCase() === "computer"); const activeWebPlayerDevice = currentDevices?.find( (d: PlayerDevice) => d.is_active && d.type.toLowerCase() === "computer" && d.name.toLowerCase().includes("web player") ); const activeDesktopPlayerDevice = currentDevices?.find( (d: PlayerDevice) => d.is_active && d.type.toLowerCase() === "computer" && !d.name.toLowerCase().includes("web player") ); const deviceData = { webPlayer, desktop, activeDevice, activeComputerDevice, activeWebPlayerDevice, activeDesktopPlayerDevice, }; return deviceData; } export function getDeviceMenuInfo() { const { webPlayer, desktop, activeDevice, activeComputerDevice, activeWebPlayerDevice } = getDeviceSet(); const devices: PlayerDevice[] = getCurrentDevices() || []; let primaryText = ""; let secondaryText = ""; let isActive = true; if (activeDevice) { // found an active device primaryText = `Listening on your ${activeDevice.name}`; } else if (isMac() && desktop) { // show that the desktop player is an active device primaryText = `Listening on your ${desktop.name}`; } else if (webPlayer) { // show that the web player is an active device primaryText = `Listening on your ${webPlayer.name}`; } else if (desktop) { // show that the desktop player is an active device primaryText = `Listening on your ${desktop.name}`; } else if (devices.length) { // no active device but found devices const names = devices.map((d: PlayerDevice) => d.name); primaryText = `Spotify devices available`; secondaryText = `${names.join(", ")}`; isActive = false; } else if (devices.length === 0) { // no active device and no devices primaryText = "Connect to a Spotify device"; secondaryText = "Launch the web or desktop player"; isActive = false; } return { primaryText, secondaryText, isActive }; } export function getBestActiveDevice() { const { webPlayer, desktop, activeDevice } = getDeviceSet(); const device = activeDevice ? activeDevice : desktop ? desktop : webPlayer ? webPlayer : null; return device; } //////////////////////////////////////////////////////////////// // PLAYER CONTEXT FUNCTIONS //////////////////////////////////////////////////////////////// export async function populatePlayerContext() { spotifyContext = await getSpotifyPlayerContext(); MusicCommandManager.syncControls(cachedRunningTrack, false); } //////////////////////////////////////////////////////////////// // UTIL FUNCTIONS //////////////////////////////////////////////////////////////// export function requiresSpotifyAccess() { const spotifyIntegration = getSpotifyIntegration(); // no spotify access token then return true, the user requires spotify access return !spotifyIntegration ? true : false; } export async function initializeSpotify(refreshUser = false) { // get the client id and secret await updateSpotifyClientInfo(); // update cody music with all access info updateCodyConfig(); // first get the spotify user await populateSpotifyUser(refreshUser); await populateSpotifyDevices(false); // initialize the status bar music controls MusicCommandManager.initialize(); } export async function isTrackRepeating(): Promise<boolean> { // get the current repeat state if (!spotifyContext) { spotifyContext = await getSpotifyPlayerContext(); } // "off", "track", "context", "" const repeatState = spotifyContext ? spotifyContext.repeat_state : ""; return repeatState && repeatState === "track" ? true : false; } export async function removeTrackFromPlaylist(trackItem: PlaylistItem) { // get the playlist it's in const currentPlaylistId = trackItem["playlist_id"]; const foundPlaylist = getPlaylistById(currentPlaylistId); if (foundPlaylist) { // if it's the liked songs, then send it to the setLiked(false) api if (foundPlaylist.id === SPOTIFY_LIKED_SONGS_PLAYLIST_NAME) { const buttonSelection = await window.showInformationMessage( `Are you sure you would like to remove '${trackItem.name}' from your '${SPOTIFY_LIKED_SONGS_PLAYLIST_NAME}' playlist?`, ...[YES_LABEL] ); if (buttonSelection === YES_LABEL) { await MusicControlManager.getInstance().setLiked(trackItem, false); } } else { // remove it from a playlist const tracks = [trackItem.id]; const result = await removeTracksFromPlaylist(currentPlaylistId, tracks); const errMsg = getCodyErrorMessage(result); if (errMsg) { window.showInformationMessage(`Unable to remove the track from your playlist. ${errMsg}`); } else { // remove it from the cached list playlistTracks[currentPlaylistId] = playlistTracks[currentPlaylistId].filter((n) => n.id !== trackItem.id); window.showInformationMessage("Song removed successfully"); commands.executeCommand("musictime.refreshMusicTimeView"); } } } } export async function followSpotifyPlaylist(playlist: PlaylistItem) { const codyResp: CodyResponse = await followPlaylist(playlist.id); if (codyResp.state === CodyResponseType.Success) { window.showInformationMessage(`Successfully following the '${playlist.name}' playlist.`); // repopulate the playlists since we've changed the state of the playlist await getSpotifyPlaylists(); commands.executeCommand("musictime.refreshMusicTimeView"); } else { window.showInformationMessage(`Unable to follow ${playlist.name}. ${codyResp.message}`, ...[OK_LABEL]); } } export async function isLikedSong(song: any) { if (!song) { return false; } const trackId = getSongId(song); if (!trackId) { return false; } if (!spotifyLikedTracks || spotifyLikedTracks.length === 0) { // fetch the liked tracks await populateLikedSongs(); } const foundSong = !!spotifyLikedTracks?.find((n) => n.id === trackId); return foundSong; } //////////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS //////////////////////////////////////////////////////////////// function getSongId(song) { if (song.id) { return createSpotifyIdFromUri(song.id); } else if (song.uri) { return createSpotifyIdFromUri(song.uri); } else if (song.song_id) { return createSpotifyIdFromUri(song.song_id); } return null; } export function createSpotifyIdFromUri(id: string) { if (id && id.indexOf("spotify:") === 0) { return id.substring(id.lastIndexOf(":") + 1); } return id; } async function getPlaylistItemTracksFromCodyResponse(codyResponse: CodyResponse): Promise<PlaylistItem[]> { let playlistItems: PlaylistItem[] = []; if (codyResponse && codyResponse.state === CodyResponseType.Success) { let paginationItem: PaginationItem = codyResponse.data; if (paginationItem && paginationItem.items) { let idx = 1; for await (const t of paginationItem.items) { const playlistItem: PlaylistItem = createPlaylistItemFromTrack(t, idx); playlistItem["liked"] = await isLikedSong(t); playlistItems.push(playlistItem); idx++; } } } return playlistItems; } export function createPlaylistItemFromTrack(track: Track, position: number = undefined) { if (position === undefined) { position = track.track_number; } let playlistItem: PlaylistItem = new PlaylistItem(); playlistItem.type = "track"; playlistItem.name = track.name; playlistItem.tooltip = getTrackTooltip(track); playlistItem.id = track.id; playlistItem.uri = track.uri; playlistItem.popularity = track.popularity; playlistItem.position = position; playlistItem.artist = getArtist(track); playlistItem.playerType = track.playerType; playlistItem.itemType = "track"; playlistItem["albumId"] = track?.album?.id; playlistItem["albumName"] = getAlbumName(track); playlistItem["description"] = getArtistAlbumDescription(track); delete playlistItem.tracks; return playlistItem; } function getTrackTooltip(track: any) { let tooltip = track.name; const artistName = getArtist(track); if (artistName) { tooltip += ` - ${artistName}`; } if (track.popularity) { tooltip += ` (Popularity: ${track.popularity})`; } return tooltip; } function getArtistAlbumDescription(track: any) { let artistName = getArtist(track); let albumName = getAlbumName(track); // return artist - album (but abbreviate both if the len is too large) if (artistName && albumName && artistName.length + albumName.length > 100) { // start abbreviating if (artistName.length > 50) { artistName = artistName.substring(0, 50) + "..."; } if (albumName.length > 50) { albumName = albumName.substring(0, 50) + "..."; } } return albumName ? `${artistName} - ${albumName}` : artistName; } function getArtist(track: any) { if (!track) { return null; } if (track.artist) { return track.artist; } if (track.artists && track.artists.length > 0) { const trackArtist = track.artists[0]; return trackArtist.name; } return null; } async function getTrackIdsForRecommendations(seedLimit: number = 5, seedTracks = [], offset = 0) { if (seedLimit === 0) { return []; } if (!spotifyLikedTracks) { await populateLikedSongs(); } seedLimit = offset + seedLimit; // up until limit if (spotifyLikedTracks?.length) { if (offset > spotifyLikedTracks.length - 1) { offset = 0; } seedTracks.push(...spotifyLikedTracks.slice(offset, seedLimit)); } const remainingLen = seedLimit - seedTracks.length; if (remainingLen < seedLimit) { // find a few more Object.keys(playlistTracks).every((playlist_id) => { if (playlist_id !== SPOTIFY_LIKED_SONGS_PLAYLIST_ID && playlistTracks[playlist_id] && playlistTracks[playlist_id].length >= remainingLen) { seedTracks.push(...playlistTracks[playlist_id].splice(0, remainingLen)); return; } }); } let trackIds = seedTracks.map((n) => n.id); return trackIds; } function getAlbumName(track) { let albumName = track["albumName"]; if (!albumName && track["album"] && track["album"].name) { albumName = track["album"].name; } return albumName; } export function sortPlaylists(playlists, alphabetically = sortAlphabetically) { if (playlists && playlists.length > 0) { playlists.sort((a: PlaylistItem, b: PlaylistItem) => { if (alphabetically) { const nameA = a.name.toLowerCase(), nameB = b.name.toLowerCase(); if (nameA < nameB) //sort string ascending return -1; if (nameA > nameB) return 1; return 0; // default return value (no sorting) } else { const indexA = a["index"], indexB = b["index"]; if (indexA < indexB) // sort ascending return -1; if (indexA > indexB) return 1; return 0; // default return value (no sorting) } }); } } function sortTracks(tracks) { if (tracks && tracks.length > 0) { tracks.sort((a: Track, b: Track) => { const nameA = a.name.toLowerCase(), nameB = b.name.toLowerCase(); if (nameA < nameB) //sort string ascending return -1; if (nameA > nameB) return 1; return 0; //default return value (no sorting) }); } }
the_stack
"use strict"; import tm = require("./projectManager"); import tu = require("./testUtil"); import su = require("./serverUtil"); import platform = require("./platform"); import path = require("path"); import os = require("os"); import assert = require("assert"); import Q = require("q"); var express = require("express"); var bodyparser = require("body-parser"); var projectManager = tm.ProjectManager; var testUtil = tu.TestUtil; var templatePath = path.join(__dirname, "../../test/template"); var thisPluginPath = path.join(__dirname, "../.."); var testRunDirectory = path.join(os.tmpdir(), "cordova-plugin-code-push", "test-run"); var updatesDirectory = path.join(os.tmpdir(), "cordova-plugin-code-push", "updates"); var serverUrl = testUtil.readMockServerName(); var targetEmulator = testUtil.readTargetEmulator(); var targetPlatform: platform.IPlatform = platform.PlatformResolver.resolvePlatform(testUtil.readTargetPlatform()); const AndroidKey = "mock-android-deployment-key"; const IOSKey = "mock-ios-deployment-key"; const TestAppName = "TestCodePush"; const TestNamespace = "com.microsoft.codepush.test"; const AcquisitionSDKPluginName = "code-push"; const ScenarioCheckForUpdatePath = "js/scenarioCheckForUpdate.js"; const ScenarioDownloadUpdate = "js/scenarioDownloadUpdate.js"; const ScenarioApply = "js/scenarioApply.js"; const ScenarioApplyWithRevert = "js/scenarioApplyWithRevert.js"; const ScenarioSync = "js/scenarioSync.js"; const ScenarioSyncWithRevert = "js/scenarioSyncWithRevert.js"; const UpdateDeviceReady = "js/updateDeviceReady.js"; const UpdateNotifyApplicationReady = "js/updateNotifyApplicationReady.js"; const UpdateSync = "js/updateSync.js"; var app: any; var server: any; var mockResponse: any; var testMessageCallback: (requestBody: any) => void; var mockUpdatePackagePath: string; function cleanupScenario() { if (server) { server.close(); server = undefined; } } function setupScenario(scenarioPath: string): Q.Promise<void> { console.log("\nScenario: " + scenarioPath); console.log("Mock server url: " + serverUrl); console.log("Target platform: " + targetPlatform ? targetPlatform.getCordovaName() : ""); console.log("Target emulator: " + targetEmulator); app = express(); app.use(bodyparser.json()); app.use(bodyparser.urlencoded({ extended: true })); app.get("/updateCheck", function(req: any, res: any) { res.send(mockResponse); console.log("Update check called from the app."); }); app.get("/download", function(req: any, res: any) { res.download(mockUpdatePackagePath); }); app.post("/reportTestMessage", function(req: any, res: any) { console.log("Application reported a test message."); console.log("Body: " + JSON.stringify(req.body)); res.sendStatus(200); testMessageCallback(req.body); }); server = app.listen(3000); return projectManager.setupTemplate(testRunDirectory, templatePath, serverUrl, AndroidKey, IOSKey, TestAppName, TestNamespace, scenarioPath) .then<void>(() => { return projectManager.addPlatform(testRunDirectory, targetPlatform); }) .then<void>(() => { return projectManager.addPlugin(testRunDirectory, AcquisitionSDKPluginName); }) .then<void>(() => { return projectManager.addPlugin(testRunDirectory, thisPluginPath); }) .then<void>(() => { return projectManager.buildPlatform(testRunDirectory, targetPlatform); }); } function createDefaultResponse(): su.CheckForUpdateResponseMock { var defaultReponse = new su.CheckForUpdateResponseMock(); defaultReponse.downloadURL = ""; defaultReponse.description = ""; defaultReponse.isAvailable = false; defaultReponse.isMandatory = false; defaultReponse.appVersion = ""; defaultReponse.packageHash = ""; defaultReponse.label = ""; defaultReponse.packageSize = 0; defaultReponse.updateAppVersion = false; return defaultReponse; } function createMockResponse(): su.CheckForUpdateResponseMock { var updateReponse = new su.CheckForUpdateResponseMock(); updateReponse.isAvailable = true; updateReponse.appVersion = "1.0.0"; updateReponse.downloadURL = "mock.url/download"; updateReponse.isMandatory = true; updateReponse.label = "mock-update"; updateReponse.packageHash = "12345-67890"; updateReponse.packageSize = 12345; updateReponse.updateAppVersion = false; return updateReponse; } var getMockResponse = (randomHash: boolean): su.CheckForUpdateResponseMock => { var updateReponse = createMockResponse(); updateReponse.downloadURL = serverUrl + "/download"; /* for some tests we need unique hashes to avoid conflicts - the application is not uninstalled between tests and we store the failed hashes in preferences */ if (randomHash) { updateReponse.packageHash = "randomHash-" + Math.floor(Math.random() * 1000); } return updateReponse; }; function setupUpdateProject(scenarioPath: string, version: string): Q.Promise<void> { console.log("Creating an update at location: " + updatesDirectory); return projectManager.setupTemplate(updatesDirectory, templatePath, serverUrl, AndroidKey, IOSKey, TestAppName, TestNamespace, scenarioPath, version) .then<void>(() => { return projectManager.addPlatform(updatesDirectory, targetPlatform); }) .then<void>(() => { return projectManager.addPlugin(testRunDirectory, AcquisitionSDKPluginName); }) .then<void>(() => { return projectManager.addPlugin(updatesDirectory, thisPluginPath); }) .then<void>(() => { return projectManager.buildPlatform(updatesDirectory, targetPlatform); }); }; function verifyMessages(expectedMessages: (string | su.AppMessage)[], deferred: Q.Deferred<void>): (requestBody: any) => void { var messageIndex = 0; return (requestBody: su.AppMessage) => { try { console.log("Message index: " + messageIndex); if (typeof expectedMessages[messageIndex] === "string") { assert.equal(expectedMessages[messageIndex], requestBody.message); } else { assert(su.areEqual(<su.AppMessage>expectedMessages[messageIndex], requestBody)); } /* end of message array */ if (++messageIndex === expectedMessages.length) { deferred.resolve(undefined); } } catch (e) { deferred.reject(e); } }; }; describe("window.codePush", function() { this.timeout(100 * 60 * 1000); /* clean up */ afterEach(() => { console.log("Cleaning up!"); mockResponse = undefined; testMessageCallback = undefined; }); describe("#window.codePush.checkForUpdate", function() { before(() => { return setupScenario(ScenarioCheckForUpdatePath); }); after(() => { cleanupScenario(); }); it("should handle no update scenario", function(done) { var noUpdateReponse = createDefaultResponse(); noUpdateReponse.isAvailable = false; noUpdateReponse.appVersion = "0.0.1"; mockResponse = { updateInfo: noUpdateReponse }; testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.CHECK_UP_TO_DATE, requestBody.message); done(); } catch (e) { done(e); } }; console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); }); it("should return no update in updateAppVersion scenario", function(done) { var updateAppVersionReponse = createDefaultResponse(); updateAppVersionReponse.updateAppVersion = true; updateAppVersionReponse.appVersion = "2.0.0"; mockResponse = { updateInfo: updateAppVersionReponse }; testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.CHECK_UP_TO_DATE, requestBody.message); done(); } catch (e) { done(e); } }; console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); }); it("should handle update scenario", function(done) { var updateReponse = createMockResponse(); mockResponse = { updateInfo: updateReponse }; testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.CHECK_UPDATE_AVAILABLE, requestBody.message); assert.notEqual(null, requestBody.args[0]); var remotePackage: IRemotePackage = requestBody.args[0]; assert.equal(remotePackage.downloadUrl, updateReponse.downloadURL); assert.equal(remotePackage.isMandatory, updateReponse.isMandatory); assert.equal(remotePackage.label, updateReponse.label); assert.equal(remotePackage.packageHash, updateReponse.packageHash); assert.equal(remotePackage.packageSize, updateReponse.packageSize); done(); } catch (e) { done(e); } }; console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); }); it("should handle error during check for update scenario", function(done) { mockResponse = "invalid {{ json"; testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.CHECK_ERROR, requestBody.message); done(); } catch (e) { done(e); } }; console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); }); }); describe("#remotePackage.download", function() { before(() => { return setupScenario(ScenarioDownloadUpdate); }); after(() => { cleanupScenario(); }); var getMockResponse = (): su.CheckForUpdateResponseMock => { var updateReponse = createMockResponse(); updateReponse.downloadURL = serverUrl + "/download"; return updateReponse; }; it("should successfully download new updates", function(done) { mockResponse = { updateInfo: getMockResponse() }; /* pass the path to any file for download (here, config.xml) to make sure the download completed callback is invoked */ mockUpdatePackagePath = path.join(templatePath, "config.xml"); testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.DOWNLOAD_SUCCEEDED, requestBody.message); done(); } catch (e) { done(e); } }; console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); }); it("should handle errors during download", function(done) { mockResponse = { updateInfo: getMockResponse() }; /* pass an invalid path */ mockUpdatePackagePath = path.join(templatePath, "invalid_path.zip"); testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.DOWNLOAD_ERROR, requestBody.message); done(); } catch (e) { done(e); } }; console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); }); }); describe("#localPackage.apply", function() { after(() => { cleanupScenario(); }); before(() => { return setupScenario(ScenarioApply); }); var getMockResponse = (): su.CheckForUpdateResponseMock => { var updateReponse = createMockResponse(); updateReponse.downloadURL = serverUrl + "/download"; return updateReponse; }; it("should handle unzip errors", function(done) { mockResponse = { updateInfo: getMockResponse() }; /* pass an invalid zip file, here, config.xml */ mockUpdatePackagePath = path.join(templatePath, "config.xml"); testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.APPLY_ERROR, requestBody.message); done(); } catch (e) { done(e); } }; console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); }); it("should handle apply", function(done) { mockResponse = { updateInfo: getMockResponse() }; /* create an update */ setupUpdateProject(UpdateDeviceReady, "Update 1") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.APPLY_SUCCESS, su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); return deferred.promise; }) .done(done, done); }); }); describe("#localPackage.apply (with revert)", function() { after(() => { cleanupScenario(); }); before(() => { return setupScenario(ScenarioApplyWithRevert); }); it("should handle revert", function(done) { mockResponse = { updateInfo: getMockResponse(false) }; /* create an update */ setupUpdateProject(UpdateDeviceReady, "Update 1 (bad update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.APPLY_SUCCESS, su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.UPDATE_FAILED_PREVIOUSLY], deferred); console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); return deferred.promise; }) .then<void>(() => { /* create a second failed update */ console.log("Creating a second failed update."); var deferred = Q.defer<void>(); mockResponse = { updateInfo: getMockResponse(true) }; testMessageCallback = verifyMessages([su.TestMessage.APPLY_SUCCESS, su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.UPDATE_FAILED_PREVIOUSLY], deferred); console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); return deferred.promise; }) .done(done, done); }); it("should not revert on success", function(done) { mockResponse = { updateInfo: getMockResponse(true) }; /* create an update */ setupUpdateProject(UpdateNotifyApplicationReady, "Update 1 (good update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.APPLY_SUCCESS, su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS, su.TestMessage.APPLICATION_NOT_REVERTED], deferred); console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); return deferred.promise; }) .done(done, done); }); }); describe("#window.codePush.sync (no revert)", function() { after(() => { cleanupScenario(); }); before(() => { return setupScenario(ScenarioSync); }); it("sync should handle no update scenario", function(done) { var noUpdateReponse = createDefaultResponse(); noUpdateReponse.isAvailable = false; noUpdateReponse.appVersion = "0.0.1"; mockResponse = { updateInfo: noUpdateReponse }; testMessageCallback = (requestBody: any) => { try { assert(su.areEqual(requestBody, new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UP_TO_DATE]))); done(); } catch (e) { done(e); } }; console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); }); it("should handle error during check for update scenario", function(done) { mockResponse = "invalid {{ json"; testMessageCallback = (requestBody: any) => { try { assert(su.areEqual(requestBody, new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_ERROR]))); done(); } catch (e) { done(e); } }; console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); }); it("should handle errors during download", function(done) { var invalidUrlResponse = createMockResponse(); invalidUrlResponse.downloadURL = path.join(templatePath, "invalid_path.zip"); mockResponse = { updateInfo: invalidUrlResponse }; testMessageCallback = (requestBody: any) => { try { assert(su.areEqual(requestBody, new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_ERROR]))); done(); } catch (e) { done(e); } }; console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); }); it("sync should apply when update available", function(done) { mockResponse = { updateInfo: getMockResponse(false) }; /* create an update */ setupUpdateProject(UpdateDeviceReady, "Update 1 (good update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_APPLY_SUCCESS]), su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); return deferred.promise; }) .done(done, done); }); }); describe("#window.codePush.sync (with revert)", function() { after(() => { cleanupScenario(); }); before(() => { return setupScenario(ScenarioSyncWithRevert); }); it("sync should handle revert", function(done) { mockResponse = { updateInfo: getMockResponse(false) }; /* create an update */ setupUpdateProject(UpdateDeviceReady, "Update 1 (bad update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_APPLY_SUCCESS]), su.TestMessage.DEVICE_READY_AFTER_UPDATE, new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UP_TO_DATE])], deferred); console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); return deferred.promise; }) .done(done, done); }); it("sync should not revert on success", function(done) { mockResponse = { updateInfo: getMockResponse(true) }; /* create an update */ setupUpdateProject(UpdateSync, "Update 1 (good update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_APPLY_SUCCESS]), su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.APPLICATION_NOT_REVERTED], deferred); console.log("Running project..."); projectManager.runPlatform(testRunDirectory, targetPlatform, true, targetEmulator); return deferred.promise; }) .done(done, done); }); }); });
the_stack
*/ export enum LabelKind { Int, Text, } /** */ export enum SignedMessageKind { COSESIGN, COSESIGN1, } /** */ export enum SigContext { Signature, Signature1, CounterSignature, } /** */ export enum CBORSpecialType { Bool, Float, Unassigned, Break, Undefined, Null, } /** */ export enum CBORValueKind { Int, Bytes, Text, Array, Object, TaggedCBOR, Special, } /** */ export enum AlgorithmId { /** *r" EdDSA (Pure EdDSA, not HashedEdDSA) - the algorithm used for Cardano addresses */ EdDSA, /** *r" ChaCha20/Poly1305 w/ 256-bit key, 128-bit tag */ ChaCha20Poly1305, } /** */ export enum KeyType { /** *r" octet key pair */ OKP, /** *r" 2-coord EC */ EC2, Symmetric, } /** */ export enum ECKey { CRV, X, Y, D, } /** */ export enum CurveType { P256, P384, P521, X25519, X448, Ed25519, Ed448, } /** */ export enum KeyOperation { Sign, Verify, Encrypt, Decrypt, WrapKey, UnwrapKey, DeriveKey, DeriveBits, } /** */ export class BigNum { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {BigNum} */ static from_bytes(bytes: Uint8Array): BigNum; /** * @param {string} string * @returns {BigNum} */ static from_str(string: string): BigNum; /** * @returns {string} */ to_str(): string; /** * @param {BigNum} other * @returns {BigNum} */ checked_mul(other: BigNum): BigNum; /** * @param {BigNum} other * @returns {BigNum} */ checked_add(other: BigNum): BigNum; /** * @param {BigNum} other * @returns {BigNum} */ checked_sub(other: BigNum): BigNum; } /** */ export class CBORArray { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {CBORArray} */ static from_bytes(bytes: Uint8Array): CBORArray; /** * @returns {CBORArray} */ static new(): CBORArray; /** * @returns {number} */ len(): number; /** * @param {number} index * @returns {CBORValue} */ get(index: number): CBORValue; /** * @param {CBORValue} elem */ add(elem: CBORValue): void; /** * @param {boolean} use_definite */ set_definite_encoding(use_definite: boolean): void; /** * @returns {boolean} */ is_definite(): boolean; } /** */ export class CBORObject { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {CBORObject} */ static from_bytes(bytes: Uint8Array): CBORObject; /** * @returns {CBORObject} */ static new(): CBORObject; /** * @returns {number} */ len(): number; /** * @param {CBORValue} key * @param {CBORValue} value * @returns {CBORValue | undefined} */ insert(key: CBORValue, value: CBORValue): CBORValue | undefined; /** * @param {CBORValue} key * @returns {CBORValue | undefined} */ get(key: CBORValue): CBORValue | undefined; /** * @returns {CBORArray} */ keys(): CBORArray; /** * @param {boolean} use_definite */ set_definite_encoding(use_definite: boolean): void; /** * @returns {boolean} */ is_definite(): boolean; } /** */ export class CBORSpecial { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {CBORSpecial} */ static from_bytes(bytes: Uint8Array): CBORSpecial; /** * @param {boolean} b * @returns {CBORSpecial} */ static new_bool(b: boolean): CBORSpecial; /** * @param {number} u * @returns {CBORSpecial} */ static new_unassigned(u: number): CBORSpecial; /** * @returns {CBORSpecial} */ static new_break(): CBORSpecial; /** * @returns {CBORSpecial} */ static new_null(): CBORSpecial; /** * @returns {CBORSpecial} */ static new_undefined(): CBORSpecial; /** * @returns {number} */ kind(): number; /** * @returns {boolean | undefined} */ as_bool(): boolean | undefined; /** * @returns {number | undefined} */ as_float(): number | undefined; /** * @returns {number | undefined} */ as_unassigned(): number | undefined; } /** */ export class CBORValue { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {CBORValue} */ static from_bytes(bytes: Uint8Array): CBORValue; /** * @param {Int} int * @returns {CBORValue} */ static new_int(int: Int): CBORValue; /** * @param {Uint8Array} bytes * @returns {CBORValue} */ static new_bytes(bytes: Uint8Array): CBORValue; /** * @param {string} text * @returns {CBORValue} */ static new_text(text: string): CBORValue; /** * @param {CBORArray} arr * @returns {CBORValue} */ static new_array(arr: CBORArray): CBORValue; /** * @param {CBORObject} obj * @returns {CBORValue} */ static new_object(obj: CBORObject): CBORValue; /** * @param {TaggedCBOR} tagged * @returns {CBORValue} */ static new_tagged(tagged: TaggedCBOR): CBORValue; /** * @param {CBORSpecial} special * @returns {CBORValue} */ static new_special(special: CBORSpecial): CBORValue; /** * @returns {number} */ kind(): number; /** * @returns {Int | undefined} */ as_int(): Int | undefined; /** * @returns {Uint8Array | undefined} */ as_bytes(): Uint8Array | undefined; /** * @returns {string | undefined} */ as_text(): string | undefined; /** * @returns {CBORArray | undefined} */ as_array(): CBORArray | undefined; /** * @returns {CBORObject | undefined} */ as_object(): CBORObject | undefined; /** * @returns {TaggedCBOR | undefined} */ as_tagged(): TaggedCBOR | undefined; /** * @returns {CBORSpecial | undefined} */ as_special(): CBORSpecial | undefined; } /** */ export class COSEEncrypt { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {COSEEncrypt} */ static from_bytes(bytes: Uint8Array): COSEEncrypt; /** * @returns {Headers} */ headers(): Headers; /** * @returns {Uint8Array | undefined} */ ciphertext(): Uint8Array | undefined; /** * @returns {COSERecipients} */ recipients(): COSERecipients; /** * @param {Headers} headers * @param {Uint8Array | undefined} ciphertext * @param {COSERecipients} recipients * @returns {COSEEncrypt} */ static new(headers: Headers, ciphertext: Uint8Array | undefined, recipients: COSERecipients): COSEEncrypt; } /** */ export class COSEEncrypt0 { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {COSEEncrypt0} */ static from_bytes(bytes: Uint8Array): COSEEncrypt0; /** * @returns {Headers} */ headers(): Headers; /** * @returns {Uint8Array | undefined} */ ciphertext(): Uint8Array | undefined; /** * @param {Headers} headers * @param {Uint8Array | undefined} ciphertext * @returns {COSEEncrypt0} */ static new(headers: Headers, ciphertext?: Uint8Array): COSEEncrypt0; } /** */ export class COSEKey { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {COSEKey} */ static from_bytes(bytes: Uint8Array): COSEKey; /** * @param {Label} key_type */ set_key_type(key_type: Label): void; /** * @returns {Label} */ key_type(): Label; /** * @param {Uint8Array} key_id */ set_key_id(key_id: Uint8Array): void; /** * @returns {Uint8Array | undefined} */ key_id(): Uint8Array | undefined; /** * @param {Label} algorithm_id */ set_algorithm_id(algorithm_id: Label): void; /** * @returns {Label | undefined} */ algorithm_id(): Label | undefined; /** * @param {Labels} key_ops */ set_key_ops(key_ops: Labels): void; /** * @returns {Labels | undefined} */ key_ops(): Labels | undefined; /** * @param {Uint8Array} base_init_vector */ set_base_init_vector(base_init_vector: Uint8Array): void; /** * @returns {Uint8Array | undefined} */ base_init_vector(): Uint8Array | undefined; /** * @param {Label} label * @returns {CBORValue | undefined} */ header(label: Label): CBORValue | undefined; /** * @param {Label} label * @param {CBORValue} value */ set_header(label: Label, value: CBORValue): void; /** * @param {Label} key_type * @returns {COSEKey} */ static new(key_type: Label): COSEKey; } /** */ export class COSERecipient { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {COSERecipient} */ static from_bytes(bytes: Uint8Array): COSERecipient; /** * @returns {Headers} */ headers(): Headers; /** * @returns {Uint8Array | undefined} */ ciphertext(): Uint8Array | undefined; /** * @param {Headers} headers * @param {Uint8Array | undefined} ciphertext * @returns {COSERecipient} */ static new(headers: Headers, ciphertext?: Uint8Array): COSERecipient; } /** */ export class COSERecipients { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {COSERecipients} */ static from_bytes(bytes: Uint8Array): COSERecipients; /** * @returns {COSERecipients} */ static new(): COSERecipients; /** * @returns {number} */ len(): number; /** * @param {number} index * @returns {COSERecipient} */ get(index: number): COSERecipient; /** * @param {COSERecipient} elem */ add(elem: COSERecipient): void; } /** */ export class COSESign { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {COSESign} */ static from_bytes(bytes: Uint8Array): COSESign; /** * @returns {Headers} */ headers(): Headers; /** * @returns {Uint8Array | undefined} */ payload(): Uint8Array | undefined; /** * @returns {COSESignatures} */ signatures(): COSESignatures; /** * @param {Headers} headers * @param {Uint8Array | undefined} payload * @param {COSESignatures} signatures * @returns {COSESign} */ static new(headers: Headers, payload: Uint8Array | undefined, signatures: COSESignatures): COSESign; } /** */ export class COSESign1 { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {COSESign1} */ static from_bytes(bytes: Uint8Array): COSESign1; /** * @returns {Headers} */ headers(): Headers; /** * @returns {Uint8Array | undefined} */ payload(): Uint8Array | undefined; /** * @returns {Uint8Array} */ signature(): Uint8Array; /** * For verifying, we will want to reverse-construct this SigStructure to check the signature against * # Arguments * * `external_aad` - External application data - see RFC 8152 section 4.3. Set to None if not using this. * @param {Uint8Array | undefined} external_aad * @param {Uint8Array | undefined} external_payload * @returns {SigStructure} */ signed_data(external_aad?: Uint8Array, external_payload?: Uint8Array): SigStructure; /** * @param {Headers} headers * @param {Uint8Array | undefined} payload * @param {Uint8Array} signature * @returns {COSESign1} */ static new(headers: Headers, payload: Uint8Array | undefined, signature: Uint8Array): COSESign1; } /** */ export class COSESign1Builder { free(): void; /** * @param {Headers} headers * @param {Uint8Array} payload * @param {boolean} is_payload_external * @returns {COSESign1Builder} */ static new(headers: Headers, payload: Uint8Array, is_payload_external: boolean): COSESign1Builder; /** */ hash_payload(): void; /** * @param {Uint8Array} external_aad */ set_external_aad(external_aad: Uint8Array): void; /** * @returns {SigStructure} */ make_data_to_sign(): SigStructure; /** * @param {Uint8Array} signed_sig_structure * @returns {COSESign1} */ build(signed_sig_structure: Uint8Array): COSESign1; } /** */ export class COSESignBuilder { free(): void; /** * @param {Headers} headers * @param {Uint8Array} payload * @param {boolean} is_payload_external * @returns {COSESignBuilder} */ static new(headers: Headers, payload: Uint8Array, is_payload_external: boolean): COSESignBuilder; /** */ hash_payload(): void; /** * @param {Uint8Array} external_aad */ set_external_aad(external_aad: Uint8Array): void; /** * @returns {SigStructure} */ make_data_to_sign(): SigStructure; /** * @param {COSESignatures} signed_sig_structure * @returns {COSESign} */ build(signed_sig_structure: COSESignatures): COSESign; } /** */ export class COSESignature { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {COSESignature} */ static from_bytes(bytes: Uint8Array): COSESignature; /** * @returns {Headers} */ headers(): Headers; /** * @returns {Uint8Array} */ signature(): Uint8Array; /** * @param {Headers} headers * @param {Uint8Array} signature * @returns {COSESignature} */ static new(headers: Headers, signature: Uint8Array): COSESignature; } /** */ export class COSESignatures { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {COSESignatures} */ static from_bytes(bytes: Uint8Array): COSESignatures; /** * @returns {COSESignatures} */ static new(): COSESignatures; /** * @returns {number} */ len(): number; /** * @param {number} index * @returns {COSESignature} */ get(index: number): COSESignature; /** * @param {COSESignature} elem */ add(elem: COSESignature): void; } /** */ export class CounterSignature { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {CounterSignature} */ static from_bytes(bytes: Uint8Array): CounterSignature; /** * @param {COSESignature} cose_signature * @returns {CounterSignature} */ static new_single(cose_signature: COSESignature): CounterSignature; /** * @param {COSESignatures} cose_signatures * @returns {CounterSignature} */ static new_multi(cose_signatures: COSESignatures): CounterSignature; /** * @returns {COSESignatures} */ signatures(): COSESignatures; } /** */ export class EdDSA25519Key { free(): void; /** * @param {Uint8Array} pubkey_bytes * @returns {EdDSA25519Key} */ static new(pubkey_bytes: Uint8Array): EdDSA25519Key; /** * @param {Uint8Array} private_key_bytes */ set_private_key(private_key_bytes: Uint8Array): void; /** */ is_for_signing(): void; /** */ is_for_verifying(): void; /** * @returns {COSEKey} */ build(): COSEKey; } /** */ export class HeaderMap { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {HeaderMap} */ static from_bytes(bytes: Uint8Array): HeaderMap; /** * @param {Label} algorithm_id */ set_algorithm_id(algorithm_id: Label): void; /** * @returns {Label | undefined} */ algorithm_id(): Label | undefined; /** * @param {Labels} criticality */ set_criticality(criticality: Labels): void; /** * @returns {Labels | undefined} */ criticality(): Labels | undefined; /** * @param {Label} content_type */ set_content_type(content_type: Label): void; /** * @returns {Label | undefined} */ content_type(): Label | undefined; /** * @param {Uint8Array} key_id */ set_key_id(key_id: Uint8Array): void; /** * @returns {Uint8Array | undefined} */ key_id(): Uint8Array | undefined; /** * @param {Uint8Array} init_vector */ set_init_vector(init_vector: Uint8Array): void; /** * @returns {Uint8Array | undefined} */ init_vector(): Uint8Array | undefined; /** * @param {Uint8Array} partial_init_vector */ set_partial_init_vector(partial_init_vector: Uint8Array): void; /** * @returns {Uint8Array | undefined} */ partial_init_vector(): Uint8Array | undefined; /** * @param {CounterSignature} counter_signature */ set_counter_signature(counter_signature: CounterSignature): void; /** * @returns {CounterSignature | undefined} */ counter_signature(): CounterSignature | undefined; /** * @param {Label} label * @returns {CBORValue | undefined} */ header(label: Label): CBORValue | undefined; /** * @param {Label} label * @param {CBORValue} value */ set_header(label: Label, value: CBORValue): void; /** * @returns {Labels} */ keys(): Labels; /** * @returns {HeaderMap} */ static new(): HeaderMap; } /** */ export class Headers { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {Headers} */ static from_bytes(bytes: Uint8Array): Headers; /** * @returns {ProtectedHeaderMap} */ protected(): ProtectedHeaderMap; /** * @returns {HeaderMap} */ unprotected(): HeaderMap; /** * @param {ProtectedHeaderMap} protected_ * @param {HeaderMap} unprotected_ * @returns {Headers} */ static new(protected_: ProtectedHeaderMap, unprotected_: HeaderMap): Headers; } /** */ export class Int { free(): void; /** * @param {BigNum} x * @returns {Int} */ static new(x: BigNum): Int; /** * @param {BigNum} x * @returns {Int} */ static new_negative(x: BigNum): Int; /** * @param {number} x * @returns {Int} */ static new_i32(x: number): Int; /** * @returns {boolean} */ is_positive(): boolean; /** * @returns {BigNum | undefined} */ as_positive(): BigNum | undefined; /** * @returns {BigNum | undefined} */ as_negative(): BigNum | undefined; /** * @returns {number | undefined} */ as_i32(): number | undefined; } /** */ export class Label { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {Label} */ static from_bytes(bytes: Uint8Array): Label; /** * @param {Int} int * @returns {Label} */ static new_int(int: Int): Label; /** * @param {string} text * @returns {Label} */ static new_text(text: string): Label; /** * @returns {number} */ kind(): number; /** * @returns {Int | undefined} */ as_int(): Int | undefined; /** * @returns {string | undefined} */ as_text(): string | undefined; /** * @param {number} id * @returns {Label} */ static from_algorithm_id(id: number): Label; /** * @param {number} key_type * @returns {Label} */ static from_key_type(key_type: number): Label; /** * @param {number} ec_key * @returns {Label} */ static from_ec_key(ec_key: number): Label; /** * @param {number} curve_type * @returns {Label} */ static from_curve_type(curve_type: number): Label; /** * @param {number} key_op * @returns {Label} */ static from_key_operation(key_op: number): Label; } /** */ export class Labels { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {Labels} */ static from_bytes(bytes: Uint8Array): Labels; /** * @returns {Labels} */ static new(): Labels; /** * @returns {number} */ len(): number; /** * @param {number} index * @returns {Label} */ get(index: number): Label; /** * @param {Label} elem */ add(elem: Label): void; } /** */ export class PasswordEncryption { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {PasswordEncryption} */ static from_bytes(bytes: Uint8Array): PasswordEncryption; /** * @param {COSEEncrypt0} data * @returns {PasswordEncryption} */ static new(data: COSEEncrypt0): PasswordEncryption; } /** */ export class ProtectedHeaderMap { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {ProtectedHeaderMap} */ static from_bytes(bytes: Uint8Array): ProtectedHeaderMap; /** * @returns {ProtectedHeaderMap} */ static new_empty(): ProtectedHeaderMap; /** * @param {HeaderMap} header_map * @returns {ProtectedHeaderMap} */ static new(header_map: HeaderMap): ProtectedHeaderMap; /** * @returns {HeaderMap} */ deserialized_headers(): HeaderMap; } /** */ export class PubKeyEncryption { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {PubKeyEncryption} */ static from_bytes(bytes: Uint8Array): PubKeyEncryption; /** * @param {COSEEncrypt} data * @returns {PubKeyEncryption} */ static new(data: COSEEncrypt): PubKeyEncryption; } /** */ export class SigStructure { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {SigStructure} */ static from_bytes(bytes: Uint8Array): SigStructure; /** * @returns {number} */ context(): number; /** * @returns {ProtectedHeaderMap} */ body_protected(): ProtectedHeaderMap; /** * @returns {ProtectedHeaderMap | undefined} */ sign_protected(): ProtectedHeaderMap | undefined; /** * @returns {Uint8Array} */ external_aad(): Uint8Array; /** * @returns {Uint8Array} */ payload(): Uint8Array; /** * @param {ProtectedHeaderMap} sign_protected */ set_sign_protected(sign_protected: ProtectedHeaderMap): void; /** * @param {number} context * @param {ProtectedHeaderMap} body_protected * @param {Uint8Array} external_aad * @param {Uint8Array} payload * @returns {SigStructure} */ static new(context: number, body_protected: ProtectedHeaderMap, external_aad: Uint8Array, payload: Uint8Array): SigStructure; } /** */ export class SignedMessage { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {SignedMessage} */ static from_bytes(bytes: Uint8Array): SignedMessage; /** * @param {COSESign} cose_sign * @returns {SignedMessage} */ static new_cose_sign(cose_sign: COSESign): SignedMessage; /** * @param {COSESign1} cose_sign1 * @returns {SignedMessage} */ static new_cose_sign1(cose_sign1: COSESign1): SignedMessage; /** * @param {string} s * @returns {SignedMessage} */ static from_user_facing_encoding(s: string): SignedMessage; /** * @returns {string} */ to_user_facing_encoding(): string; /** * @returns {number} */ kind(): number; /** * @returns {COSESign | undefined} */ as_cose_sign(): COSESign | undefined; /** * @returns {COSESign1 | undefined} */ as_cose_sign1(): COSESign1 | undefined; } /** */ export class TaggedCBOR { free(): void; /** * @returns {Uint8Array} */ to_bytes(): Uint8Array; /** * @param {Uint8Array} bytes * @returns {TaggedCBOR} */ static from_bytes(bytes: Uint8Array): TaggedCBOR; /** * @returns {BigNum} */ tag(): BigNum; /** * @returns {CBORValue} */ value(): CBORValue; /** * @param {BigNum} tag * @param {CBORValue} value * @returns {TaggedCBOR} */ static new(tag: BigNum, value: CBORValue): TaggedCBOR; }
the_stack
import {Component, EventEmitter, Inject, OnInit, Output} from '@angular/core'; import {FilterAuditModel} from '../filter-audit.model'; import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from '@angular/material/dialog'; import {AuditService} from '../../../core/services/audit.service'; import {SortUtils} from '../../../core/util'; import {CompareUtils} from '../../../core/util/compareUtils'; export interface AuditItem { action: string; info: string; project: string; resourceName: string; timestamp: number; type: string; user: string; _id: string; } @Component({ selector: 'datalab-audit-grid', templateUrl: './audit-grid.component.html', styleUrls: ['./audit-grid.component.scss', '../../../resources/resources-grid/resources-grid.component.scss'], }) export class AuditGridComponent implements OnInit { public auditData: Array<AuditItem>; public displayedColumns: string[] = ['date', 'user', 'action', 'project', 'resource-type', 'resource', 'buttons']; public displayedFilterColumns: string[] = ['date-filter', 'user-filter', 'actions-filter', 'project-filter', 'resource-type-filter', 'resource-filter', 'filter-buttons']; public collapseFilterRow: boolean = false; public filterConfiguration: FilterAuditModel = new FilterAuditModel([], [], [], [], [], '', ''); public filterAuditData: FilterAuditModel = new FilterAuditModel([], [], [], [], [], '', ''); public itemsPrPage: Number[] = [25, 50, 100]; public showItemsPrPage: number; public firstItem: number = 1; public lastItem: number; public allItems: number; private copiedFilterAuditData: FilterAuditModel; public isNavigationDisabled: boolean; public isFilterSelected: boolean; @Output() resetDateFilter: EventEmitter<any> = new EventEmitter(); constructor( public dialogRef: MatDialogRef<AuditInfoDialogComponent>, public dialog: MatDialog, private auditService: AuditService, ) { } ngOnInit() {} public buildAuditGrid(filter?: boolean): void { if (!this.showItemsPrPage) { if (window.localStorage.getItem('audit_per_page')) { this.showItemsPrPage = +window.localStorage.getItem('audit_per_page'); } else { this.showItemsPrPage = 50; } this.lastItem = this.showItemsPrPage; } this.getAuditData(filter); } public getAuditData(filter?: boolean): void { const page = filter ? 1 : Math.ceil(this.lastItem / this.showItemsPrPage); this.copiedFilterAuditData = JSON.parse(JSON.stringify(this.filterAuditData)); this.auditService.getAuditData(this.filterAuditData, page, this.showItemsPrPage).subscribe(auditData => { if (filter) this.changePage('first'); this.auditData = auditData[0].audit; this.allItems = auditData[0]['page_count']; this.filterConfiguration = new FilterAuditModel( auditData[0].user_filter.filter(v => v), auditData[0].resource_name_filter.filter(v => v), auditData[0].resource_type_filter.filter(v => v), auditData[0].project_filter.filter(v => v), [], '', '' ); this.checkFilters(); }); } public refreshAuditPage(): void { this.filterAuditData = this.copiedFilterAuditData; this.getAuditData(); } public setAvaliblePeriod(period): void { this.filterAuditData.date_start = period.start_date; this.filterAuditData.date_end = period.end_date; this.buildAuditGrid(true); } public toggleFilterRow(): void { this.collapseFilterRow = !this.collapseFilterRow; } public onUpdate($event): void { this.filterAuditData[$event.type] = $event.model; this.checkFilters(); } private checkFilters(): void { this.isNavigationDisabled = CompareUtils.compareFilters(this.filterAuditData, this.copiedFilterAuditData); this.isFilterSelected = Object.keys(this.filterAuditData).some(v => this.filterAuditData[v].length > 0); } public openActionInfo(element: AuditItem): void { if (element.type === 'GROUP' && element.info.indexOf('role') !== -1) { this.dialog.open(AuditInfoDialogComponent, { data: { element, dialogSize: 'big' }, panelClass: 'modal-xl-m' }); } else { this.dialog.open(AuditInfoDialogComponent, { data: {element, dialogSize: 'small' }, panelClass: 'modal-md' }); } } public setItemsPrPage(item: number): void { window.localStorage.setItem('audit_per_page', item.toString()); this.firstItem = 1; if (this.lastItem !== item) { this.lastItem = item; this.buildAuditGrid(); } } private changePage(action: string): void { if (action === 'first') { this.firstItem = 1; this.lastItem = this.showItemsPrPage; } else if (action === 'previous') { this.firstItem = this.firstItem - this.showItemsPrPage; this.lastItem = this.lastItem % this.showItemsPrPage === 0 ? this.lastItem - this.showItemsPrPage : this.lastItem - (this.lastItem % this.showItemsPrPage); } else if (action === 'next') { this.firstItem = this.firstItem + this.showItemsPrPage; this.lastItem = (this.lastItem + this.showItemsPrPage) > this.allItems ? this.allItems : this.lastItem + this.showItemsPrPage; } else if (action === 'last') { this.firstItem = this.allItems % this.showItemsPrPage === 0 ? this.allItems - this.showItemsPrPage : this.allItems - (this.allItems % this.showItemsPrPage) + 1; this.lastItem = this.allItems; } } public loadItemsForPage(action: string): void { this.changePage(action); this.buildAuditGrid(); } public resetFilterConfigurations(): void { this.filterAuditData = FilterAuditModel.getDefault(); this.resetDateFilter.emit(); this.buildAuditGrid(true); } } @Component({ selector: 'audit-info-dialog', template: ` <div id="dialog-box"> <header class="dialog-header"> <h4 class="modal-title">{{data.element.action | convertaction}}</h4> <button type="button" class="close" (click)="dialogRef.close()">&times;</button> </header> <div mat-dialog-content class="content audit-info-content" [ngClass]="{'pb-40': actionList[0].length > 1}" > <mat-list *ngIf="actionList[0].length > 1 && data.element.action !== 'FOLLOW_LINK' || data.element.info.indexOf('Update quota') !== -1;else message" > <ng-container *ngIf="data.element.info.indexOf('Update quota') === -1;else quotas"> <mat-list-item class="list-header"> <div class="info-item-title" [ngClass]="{'same-column-width': data.dialogSize === 'small'}">Action</div> <div class="info-item-data" [ngClass]="{'same-column-width': data.dialogSize === 'small'}"> Description </div> </mat-list-item> <div class="scrolling-content mat-list-wrapper" id="scrolling"> <mat-list-item class="list-item" *ngFor="let action of actionList"> <div *ngIf="(data.element.action === 'upload' && action[0] === 'File(s)') || (data.element.action === 'download' && action[0] === 'File(s)');else multiAction" class="info-item-title" > File </div> <ng-template #multiAction> <div class="info-item-title" [ngClass]="{'same-column-width': data.dialogSize === 'small'}">{{action[0]}}</div> </ng-template> <div class="info-item-data" [ngClass]="{'same-column-width': data.dialogSize === 'small'}" *ngIf="action[0] === 'File(s)'" > <div class="file-description ellipsis" *ngFor="let description of action[1]?.split(',')" [matTooltip]="description" matTooltipPosition="above" > {{description}} </div> </div> <div class="info-item-data" [ngClass]="{'same-column-width': data.dialogSize === 'small'}" *ngIf="action[0] !== 'File(s)'"> <div *ngFor="let description of action[1]?.split(',')" [matTooltip]="description" class="ellipsis" [ngStyle]="description.length < 20 ? {'width' :'fit-content'} : {'width':'100%'}" matTooltipPosition="above" matTooltipClass="mat-tooltip-description" > {{description}} </div> </div> </mat-list-item> </div> </ng-container> <ng-template #quotas> <mat-list-item class="list-header"> <div class="same-column-width" >Action</div> <div class="info-item-title"> Previous value </div> <div class="info-item-quota"> New value </div> </mat-list-item> <div class="scrolling-content mat-list-wrapper" id="scrolling"> <mat-list-item class="list-item" *ngFor="let action of updateBudget"> <div class="same-column-width">{{action[0]}}</div> <div class="info-item-title"> {{action[1]}} </div> <div class="info-item-quota"> {{action[2]}} </div> </mat-list-item> </div> </ng-template> </mat-list> <ng-template #message> <div class="message-wrapper"> <p *ngIf="data.element.type !== 'COMPUTE'; else computation"> <span *ngIf="data.element.info.indexOf('Scheduled') !== -1;else notScheduledNotebook">{{data.element.action | titlecase}} by scheduler.</span> <ng-template #notScheduledNotebook> <span *ngIf="data.element.type === 'WEB_TERMINAL'">{{data.element.info}} <span class="strong">{{data.element.resourceName}}</span>.</span> <span *ngIf="data.element.type !== 'WEB_TERMINAL' && data.element.type !== 'EDGE_NODE'">{{data.element.info}}.</span> <span *ngIf="data.element.type === 'EDGE_NODE' && data.element.action === 'CREATE'"> Create edge node for endpoint <span class="strong">{{data.element.resourceName}}</span>, requested in project <span class="strong">{{data.element.project}}</span>. </span> </ng-template> </p> <ng-template #computation> <p *ngIf="data.element.info.indexOf('Scheduled') !== -1;else notScheduled"> {{data.element.action | titlecase}} by scheduler, requested for notebook <span class="strong">{{data.element.info.split(' ')[data.element.info.split(' ').length - 1] }}</span>.</p> <ng-template #notScheduled> <p> <span *ngIf="data.element.action === 'FOLLOW_LINK'">{{info.action | titlecase}} compute <span class="strong">{{info.cluster}}</span>&nbsp;<span>{{info.clusterType}}</span> link, requested for notebook <span class="strong">{{info.notebook}}</span>.</span> <span *ngIf="data.element.action !== 'FOLLOW_LINK'">{{data.element.action | titlecase}} compute <span class="strong">{{data.element.resourceName}}</span>, requested for notebook <span class="strong">{{data.element.info.split(' ')[data.element.info.split(' ').length - 1] }}</span>.</span> </p> </ng-template> </ng-template> </div> </ng-template></div> </div> `, styles: [` .content { color: #718ba6; padding: 20px 30px; font-size: 14px; font-weight: 400; margin: 0; } .pb-40 { padding-bottom: 40px; } .info .confirm-dialog { color: #607D8B; } header { display: flex; justify-content: space-between; color: #607D8B; } header h4 i { vertical-align: bottom; } header a i { font-size: 20px; } header a:hover i { color: #35afd5; cursor: pointer; } .scrolling-content{overflow-y: auto; max-height: 200px; } label{cursor: pointer} .message-wrapper{min-height: 70px;; display: flex; align-items: center} .mat-list-wrapper{padding-top: 5px;} .list-item{color: #718ba6; height: auto; line-height: 20px; font-size: 14px} .info-item-title{width: 40%; padding: 10px 0;font-size: 14px;} .info-item-quota{width: 30%; padding: 10px 0;font-size: 14px;} .list-header {padding-top: 5px;} .info-item-data{width: 60%; text-align: left; padding: 10px 0; font-size: 14px; cursor: default;} .file-description{ overflow: hidden; display: block; direction: rtl; font-size: 14px;} .same-column-width{width: 50%; padding: 10px 0; font-size: 14px;} `] }) export class AuditInfoDialogComponent { actionList: string[][]; updateBudget: string[][] = []; info; constructor( public dialogRef: MatDialogRef<AuditInfoDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: any ) { if (data.element.action === 'FOLLOW_LINK' && data.element.type === 'COMPUTE') { this.info = JSON.parse(data.element.info); } if (data.element.info.indexOf('Update quota') !== -1) { this.updateBudget = data.element.info.split('\n').reduce((acc, v, i, arr) => { const row = v.split(':').map((el, index) => { if (el.indexOf('->') !== -1) { el = el.split('->'); } else if (index === 1 && el.indexOf('->') === -1) { el = ['', el]; } return el; }); acc.push(SortUtils.flatDeep(row, 1)); return acc; }, []); // this.data.element.info.replace(/->/g, ' ').split('\n').forEach( (val, j) => { // this.updateBudget[j] = []; // val.split(' ') // .forEach((v, i, arr) => { // if (arr[0] === 'Update') { // if (i === 1) { // this.updateBudget[j].push(`${arr[0]} ${arr[1]}`); // } // if (i > 1) { // this.updateBudget[j].push(arr[i]); // } // } else { // this.updateBudget[j].push(arr[i]); // } // // }); // }); } this.actionList = data.element.info.split('\n').map(v => v.split(':')).filter(v => v[0] !== ''); } }
the_stack
import description from './description'; import { createInlineStyles } from '@eightfeet/modal'; import { store } from '~/redux/store'; import unitToPx from '~/core/unitToPx'; import { BackgroundCommonTypesOfStyleItems, BackgroundGradientTypesOfStyleItems, BackgroundGroupTypesOfStyleItems, BorderTypesOfStyleItems, BoxShadowTypesOfStyleItems, DisplayTypesOfStyleItems, UnitType, } from '~/types/appData'; import { compilePlaceholderFromDataSource } from '~/core/getDataFromSource'; import React from 'react'; import prefix from '~/core/helper/getPrefix'; interface objType { [key: string]: any; } interface resultType { result: React.CSSProperties; string: string; } export const pxToRem = (value: number) => { const rootFontsize = store.getState().controller.bestFont; const uiBaseFont = store.getState().pageData.baseFont; if (uiBaseFont && rootFontsize) { return (value / uiBaseFont) * rootFontsize; } return value; }; export const pxToVw = (value: number) => { let PVw = window.innerWidth * 0.01; return value / PVw; }; export const pxToVh = (value: number) => { let PVh = window.innerHeight * 0.01; return value / PVh; }; /** 转换为目标单位 */ export const changeToUnit = (value: any) => { // 变量单位 const unit = store.getState().pageData.unit; // 转换单位 const toUnit = store.getState().pageData.toUnit; // step1:将value值转化为px单位值 const pxNumValue = unitToPx(`${value}${unit || ''}`); // step2:value px单位转换为 toUnit单位 let unitNumValue = 0; switch (toUnit) { case 'px': unitNumValue = pxNumValue; break; case 'rem': unitNumValue = pxToRem(pxNumValue); break; case 'vh': unitNumValue = pxToVh(pxNumValue); break; case 'vw': unitNumValue = pxToVw(pxNumValue); break; default: unitNumValue = pxNumValue; } return { value: `${unitNumValue}px`, unit: toUnit || 'px' }; }; /** 获取单位 */ const getUnit: (key: string, type: string, subType?: string) => string = ( key, type, subType, ) => { let items: any[] = []; if (subType) { items = (description() as { [key: string]: any })[type][subType][key]; } else { items = (description() as { [key: string]: any })[type][key]; } if (!items) return; return items[2]; }; /** 数据单位处理 */ const conversionValue: ( value: string | number, key: string, type: string, subType?: string, ) => { value: string | undefined; unit: string | undefined } = ( value, key, type, subType, ) => { // 当前描述单位 %,deg等 const descUnit = getUnit(key, type, subType); // 变量单位 const unit = store.getState().pageData.unit; if (value === undefined || value === null) { // 空值处理 return { value: undefined, unit: undefined }; } else if (descUnit === unit) { // 此单位变量可编辑等待处理 return changeToUnit(value); // 处理可编辑单位值 } else { // 其他处理 return { value: `${value}${descUnit || ''}`, unit: descUnit }; } }; // 获取全局单位 const compileValue = (data: UnitType) => { const [value, unit] = data || []; if (!value && value !== 0) { return undefined; } // 获取运行时 const runningTimes = store.getState().runningTimes; // 处理空值 if (unit === '' || unit === null || unit === undefined) { return changeToUnit(value).value; // 自定义时允许使用runningtime } else if (unit === '-') { return compilePlaceholderFromDataSource(value.toString(), runningTimes); } else { return `${value}${unit}`; } }; /** * ------------- * 布局处理 * ------------- */ export const display = (styleObj: DisplayTypesOfStyleItems): resultType => { const result: objType = {}; // typeA const unitType = ['width', 'height', 'left', 'top', 'right', 'bottom']; // typeB const unitTypeDeep = ['margin', 'padding']; for (const key in styleObj) { if (Object.prototype.hasOwnProperty.call(styleObj, key)) { const element = styleObj[key]; if (unitType.includes(key)) { // 编译处理结果 const val = compileValue(element); if (val) { result[key] = val; } } else if (unitTypeDeep.includes(key)) { // 二次规则 const oprateData = element as UnitType[]; const hasValue = (oprateData || []).some((item) => item && !!item[0]); // 有值再做处理 if (hasValue) { const tempResult: any[] = []; oprateData.forEach((item, index) => { tempResult[index] = compileValue(item) || 0; }); result[key] = tempResult.join(' '); } } else { if (element) { result[key] = element; } } } } return { result, string: createInlineStyles(result) || '', }; }; /** * ------------- * 文字处理 * ------------- */ export const font = function (styleObj: objType): resultType { const rules: objType = { fontStyle: 'fontStyle', fontWeight: 'fontWeight', fontSize: 'fontSize', lineHeight: 'lineHeight', color: 'color', letterSP: 'letterSpacing', decoration: 'textDecoration', align: 'textAlign', }; const unitType = ['fontSize', 'lineHeight', 'letterSP']; const result: objType = {}; for (const key in styleObj) { if (Object.prototype.hasOwnProperty.call(styleObj, key)) { const element = styleObj[key]; if (unitType.includes(key)) { // 编译处理结果 const val = compileValue(element); if (val) { result[rules[key]] = val; } } else { if (element) { result[rules[key]] = element; } } } } const str = createInlineStyles(result) || ''; return { result, string: str, }; }; /** * --------------- * 背景组处理 * --------------- */ export const backgroundGroup = ( backgroundGroupObj: BackgroundGroupTypesOfStyleItems, ): resultType => { const unitType = ['sizeX', 'sizeY', 'positionX', 'positionY']; const { backgroundList, backgroundColor } = backgroundGroupObj; const backgroundResultArray: (string | string[])[] = []; if (!backgroundList?.length && backgroundColor) { const result = { backgroundColor, }; return { result: result, string: createInlineStyles(result) || '', }; } // 遍历集合 backgroundList?.forEach((background, index) => { // 暂存单项样式 const backgroundItemStyle: string[] = []; // 暂存位置 const backgroundSizePosition = ['0', '0', '/', 'auto', 'auto']; const { gradient, gradientDirections, ...otherItem } = background; // 首先处理渐变================================================================== // 渐变处理需考虑浏览器情况,做优先处理 // 获取渐变属性 // 暂存渐变结果,由于浏览器兼容差异放最后处理; const gradientLise: string[] = []; if (gradient || gradientDirections) { //渐变类型,线性或径向 let type: 'linear-gradient' | 'radial-gradient' = 'linear-gradient'; // 临时傀儡数据 const puppet: { [keys: string]: any[] } = { moz: [], webkit: [], normal: [], }; /** * 生成css渐变方法首参,(确定渐变方向/方式) * 径向方向时需要修改css方法名为 radial-gradient */ const getCssGradientFun = (directions: any): string => { switch (directions) { case 'left': return 'to right'; case 'top': return 'to bottom'; case '-45deg': return '135deg'; case 'center': type = 'radial-gradient'; return 'ellipse at center'; default: return directions; } }; // step1组装方向到puppet if (gradientDirections) { puppet.moz[0] = puppet.webkit[0] = gradientDirections; puppet.normal[0] = getCssGradientFun(gradientDirections); } // step2组装位置到puppet if (gradient) { gradient.forEach(({ color, transition }) => { if (color !== undefined && transition !== undefined) { const group = `${color} ${transition}%`; puppet.moz.push(group); puppet.webkit.push(group); puppet.normal.push(group); } }); } // 存储渐变结果 for (const key in puppet) { if (Object.prototype.hasOwnProperty.call(puppet, key)) { const resultItem = puppet[key].join(', '); if (key === 'normal') { gradientLise[2] = `${type}(${resultItem})`; } else if (key === 'moz') { gradientLise[0] = `-${key}-${type}(${resultItem})`; } else { gradientLise[1] = `-${key}-${type}(${resultItem})`; } } } } // 渐变处理结束================================================================== for (const key in otherItem) { if (Object.prototype.hasOwnProperty.call(otherItem, key)) { const element = otherItem[key]; // 处理背景位置与尺寸 if (unitType.includes(key)) { // 编译处理结果 const val = compileValue(element); if (val) { switch (key) { case 'positionX': backgroundSizePosition[0] = val; break; case 'positionY': backgroundSizePosition[1] = val; break; case 'sizeX': backgroundSizePosition[3] = val; break; case 'sizeY': backgroundSizePosition[4] = val; break; default: break; } } } if (!!element) { switch (key) { case 'repeat': case 'backgroundColor': backgroundItemStyle.push(element); break; case 'imageUrl': backgroundItemStyle.push(`url("${element}")`); break; default: break; } } } } backgroundItemStyle.push(backgroundSizePosition.join(' ')); // 背景图片时 if (background.imageUrl) { backgroundResultArray.push(backgroundItemStyle.join(' ')); } else if (background.gradient || background.gradientDirections) { // 获取当前浏览器类型 if (prefix === 'webkit') { backgroundResultArray.push( `${gradientLise[1]} ${backgroundItemStyle.join(' ')}`, ); } else if (prefix === 'moz') { backgroundResultArray.push( `${gradientLise[0]} ${backgroundItemStyle.join(' ')}`, ); } else { backgroundResultArray.push( `${gradientLise[2]} ${backgroundItemStyle.join(' ')}`, ); } } }); // 多重背景叠加时,背景色应添加到最后,https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds const result = { background: `${backgroundResultArray.join(', ')} ${ backgroundColor ? backgroundColor : '' }`, }; return { result: result, string: createInlineStyles(result) || '', }; }; /** * ------------- * 常规背景处理 * ------------- */ export const backgroundCommon = ( styleObj: BackgroundCommonTypesOfStyleItems, ): resultType => { const result: BackgroundCommonTypesOfStyleItems = {}; const unitType = ['sizeX', 'sizeY', 'positionX', 'positionY']; for (const key in styleObj) { if (Object.prototype.hasOwnProperty.call(styleObj, key)) { const element = styleObj[key]; if (unitType.includes(key)) { // 编译处理结果 const val = compileValue(element); if (val) { result[key] = val; } } else if (key === 'imageUrl') { if (element) { result[key] = `url("${element}")`; } } else { if (element) { result[key] = element; } } } } const background: any[] = [ result.backgroundColor || '' /*backgroundColor*/, result.imageUrl || '' /*imageUrl*/, result.repeat || '' /*repeat*/, result.positionX || '0' /*positionX*/, result.positionY || '0' /*positionY*/, ].filter((item) => !!item?.length); const backgroundSize: string = [ result.sizeY ? result.sizeX || 'auto' : result.sizeX || '' /*sizeX*/, result.sizeX ? result.sizeY || 'auto' : result.sizeY || '' /*sizeY*/, ] .filter((item) => !!item?.length) .join(' '); const values: any = {}; if (background?.length) { values.background = background.join(' '); } if (backgroundSize?.length) { values.backgroundSize = backgroundSize; } return { result: values, string: createInlineStyles(values) || '', }; }; /** * ------------- * 渐变背景处理 * ------------- */ export const backgroundGradient = function ( styleObj: BackgroundGradientTypesOfStyleItems, ): resultType { //渐变类型,线性或径向 let type: 'linear-gradient' | 'radial-gradient' = 'linear-gradient'; // 临时傀儡数据 const puppet: { [keys: string]: any[] } = { moz: [], webkit: [], normal: [], }; /** * 生成css渐变方法首参,(确定渐变方向/方式) * 径向方向时需要修改css方法名为 radial-gradient */ const getCssGradientFun = (directions: any): string => { switch (directions) { case 'left': return 'to right'; case 'top': return 'to bottom'; case '-45deg': return '135deg'; case 'center': type = 'radial-gradient'; return 'ellipse at center'; default: return directions; } }; const { gradientDirections, gradient } = styleObj; // step1组装方向到puppet if (gradientDirections) { puppet.moz[0] = puppet.webkit[0] = gradientDirections; puppet.normal[0] = getCssGradientFun(gradientDirections); } // step2组装位置到puppet if (gradient) { gradient.forEach(({ color, transition }) => { if (color !== undefined && transition !== undefined) { const group = `${ conversionValue(color, 'color', 'backgroundGradient', 'gradient') .value } ${ conversionValue( transition, 'transition', 'backgroundGradient', 'gradient', ).value }`; puppet.moz.push(group); puppet.webkit.push(group); puppet.normal.push(group); } }); } // 无值时 if ( puppet.moz.length === 0 || puppet.webkit.length === 0 || puppet.normal.length === 0 ) { return { result: {}, string: '', }; } // 组装css const result: objType = {}; let prefixResult = []; for (const key in puppet) { if (Object.prototype.hasOwnProperty.call(puppet, key)) { const resultItem = puppet[key].join(', '); if (key === 'normal') { prefixResult.push(`background: ${type}(${resultItem});`); result[`background`] = `${type}(${resultItem})`; } else { prefixResult.push(`background: -${key}-${type}(${resultItem});`); } } } return { result, string: prefixResult.join(' '), }; }; interface BorderCompil extends BorderTypesOfStyleItems { position?: string[]; } export const border = function (styleObj: BorderTypesOfStyleItems): resultType { // border-radius: {radiusTopLeft} {radiusTopRight} {radiusBottomLeft} {radiusBottomRight}; // border{borderPosition}: {borderWidth} {borderStyle} {borderColor}; const unitType = [ 'radiusTopLeft', 'radiusTopRight', 'radiusBottomLeft', 'radiusBottomRight', 'borderWidth', ]; const result: BorderCompil = {}; for (const key in styleObj) { if (Object.prototype.hasOwnProperty.call(styleObj, key)) { const element = styleObj[key]; if (unitType.includes(key)) { // 编译处理结果 const val = compileValue(element); if (val) { result[key] = val; } } else if (key === 'borderPosition') { const arr: any = Object.keys(element).filter( (item) => element[item] !== false, ); result.position = arr; // element } else { if (element) { result[key] = element; } } } } const values: any = {}; const borderRadiusArrays = [ result.radiusTopLeft || 0, result.radiusTopRight || 0, result.radiusBottomRight || 0, result.radiusBottomLeft || 0, ]; if (borderRadiusArrays.filter((item) => item !== 0)) { values.borderRadius = borderRadiusArrays.join(' '); } if (result.position?.length !== 0) { result.position?.forEach((item) => { values[item] = [ result.borderWidth || '', result.borderStyle || '', result.borderColor, ].join(' '); }); } return { result: values, string: createInlineStyles(values) || '', }; }; export const boxShadow = function ( boxShadowArray: (BoxShadowTypesOfStyleItems & { hiddenItem: boolean })[], ): resultType { const position: objType = { inset: 0, shiftRight: 1, shiftDown: 2, blur: 3, spread: 4, color: 5, }; const rules: any[] = []; const unitType: string[] = ['blur', 'shiftDown', 'shiftRight', 'spread']; boxShadowArray.forEach((boxShadowItem: objType) => { let rule: any[] = []; rule.length = 6; for (const key in boxShadowItem) { if (Object.prototype.hasOwnProperty.call(boxShadowItem, key)) { const element = boxShadowItem[key]; if (unitType.includes(key)) { // 编译处理结果 const val = compileValue(element); if (val) { rule[position[key]] = val; } } else if (key !== 'hiddenItem') { if (element || element === false) { rule[position[key]] = element; } } } } rule[0] = !!rule[0] ? 'inset' : null; if (!rule[1]) rule[1] = '0'; if (!rule[2]) rule[2] = '0'; if (!rule[3]) rule[3] = '0'; if (!rule[4]) rule[4] = '0'; if (rule[5]) { rules.push(rule.filter((e) => !!e).join(' ')); } }); const result: objType = {}; result.boxShadow = rules.join(', '); const prefixResult = []; const str = createInlineStyles(result); prefixResult.push(`-webkit-${str}`); prefixResult.push(str); return { result, string: prefixResult.join(''), }; }; export const textShadow = function (textShadowArray: objType): resultType { // -webkit-text-shadow:{shiftRight} {blur} {shiftDown} {color}; // text-shadow:{shiftRight} {shiftDown} {blur} {color}; const position: { [keys: string]: any; } = { shiftRight: 0, shiftDown: 1, blur: 2, color: 3, }; const rules: any[] = []; const unitType: string[] = ['blur', 'shiftDown', 'shiftRight']; textShadowArray.forEach((textShadowItem: objType) => { let rule: any[] = []; rule.length = 4; for (const key in textShadowItem) { if (Object.prototype.hasOwnProperty.call(textShadowItem, key)) { const element = textShadowItem[key]; if (unitType.includes(key)) { // 编译处理结果 const val = compileValue(element); if (val) { rule[position[key]] = val; } } else if (key !== 'hiddenItem') { if (element || element === false) { rule[position[key]] = element; } } } } if (!rule[0]) rule[0] = '0'; if (!rule[1]) rule[1] = '0'; if (!rule[2]) rule[2] = '0'; if (rule[3]) { rules.push(rule.filter((e) => !!e).join(' ')); } }); const result: { [keys: string]: any; } = {}; result.textShadow = rules.join(', '); const str = createInlineStyles(result); const prefixResult = []; prefixResult.push(`-webkit-${str}`); prefixResult.push(str); return { result, string: prefixResult.join(''), }; }; export const transform = function (styleObj: objType): resultType { const position: objType = { scale: 0, rotate: 1, translate: 2, skew: 3, }; const singleProp: objType = { scale: (value: string) => `scale(${value})`, rotate: (value: string) => `rotate(${value}deg)`, }; const unitType: string[] = ['translateX', 'translateY']; const rules: any[] = []; let translateRule: any[] = [null, null]; let skewRule: any[] = [null, null]; rules.length = 4; const result: objType = {}; for (const key in styleObj) { if (Object.prototype.hasOwnProperty.call(styleObj, key)) { const element = styleObj[key]; if (unitType.includes(key)) { // 编译处理结果 const val = compileValue(element); if (val) { // {translateX}, {translateY}) skew({skewX}, {skewY} if (key === 'translateX') translateRule[0] = val; if (key === 'translateY') translateRule[1] = val; } } else { if (element) { if (singleProp[key]) { rules[position[key]] = singleProp[key](element); } if (key === 'skewX') skewRule[0] = `${element}deg`; if (key === 'skewY') skewRule[1] = `${element}deg`; } } } } let translate, skew; translate = translateRule .map((item) => { if (!item) { return '0'; } return item; }) .join(', '); skew = skewRule .map((item) => { if (!item) { return '0'; } return item; }) .join(', '); if (translate !== '0, 0') rules[position['translate']] = `translate(${translate})`; if (skew !== '0, 0') rules[position['skew']] = `skew(${skew})`; result['transform'] = rules.filter((item) => !!item).join(' '); const str = createInlineStyles(result); const prefixResult = []; prefixResult.push(`-moz-${str}`); prefixResult.push(`-webkit-${str}`); prefixResult.push(str); return { result, string: prefixResult.join(' '), }; }; export const animation = function (styleObj: objType): resultType { const position: objType = { animationName: 0, animationDuration: 1, animationTimingFunction: 2, animationDelay: 3, animationIterationCount: 4, animationDirection: 5, animationFillMode: 6, }; const rules: any[] = []; const result = {}; if (styleObj?.animationName) { for (const key in styleObj) { if (Object.prototype.hasOwnProperty.call(styleObj, key)) { const element = styleObj[key]; switch (key) { case 'animationDuration': result[key] = `${element}ms`; break; case 'animationDelay': result[key] = `${element}ms`; break; default: result[key] = element; break; } } } } return { result, string: createInlineStyles(result) || '', }; };
the_stack